要在java中接入通义千问api,请按以下步骤操作:
1. 准备工作
- 获取api key:登录阿里云dashscope控制台创建api key
- 添加依赖:在
pom.xml中添加apache httpclient和json库依赖
<dependency>
<groupid>org.apache.httpcomponents</groupid>
<artifactid>httpclient</artifactid>
<version>4.5.13</version>
</dependency>
<dependency>
<groupid>org.json</groupid>
<artifactid>json</artifactid>
<version>20231013</version>
</dependency>2. 完整代码示例
import org.apache.http.httpentity;
import org.apache.http.client.methods.closeablehttpresponse;
import org.apache.http.client.methods.httppost;
import org.apache.http.entity.stringentity;
import org.apache.http.impl.client.closeablehttpclient;
import org.apache.http.impl.client.httpclients;
import org.apache.http.util.entityutils;
import org.json.jsonobject;
public class tongyiqianwenclient {
// 从环境变量获取api key(推荐)
private static final string api_key = system.getenv("dashscope_api_key");
private static final string api_url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
public static void main(string[] args) {
try {
string response = callqianwenapi("解释一下量子计算");
system.out.println("api 响应:\n" + response);
} catch (exception e) {
e.printstacktrace();
}
}
public static string callqianwenapi(string userinput) throws exception {
// 1. 创建http客户端
try (closeablehttpclient httpclient = httpclients.createdefault()) {
// 2. 构建请求
httppost httppost = new httppost(api_url);
httppost.setheader("authorization", "bearer " + api_key);
httppost.setheader("content-type", "application/json");
httppost.setheader("x-dashscope-sse", "enable"); // 启用流式输出(可选)
// 3. 构建请求体
jsonobject requestbody = new jsonobject();
requestbody.put("model", "qwen-turbo"); // 模型名称
jsonobject input = new jsonobject();
jsonobject message = new jsonobject();
message.put("role", "user");
message.put("content", userinput);
input.put("messages", new object[]{message});
jsonobject parameters = new jsonobject();
parameters.put("result_format", "text"); // 返回纯文本格式
requestbody.put("input", input);
requestbody.put("parameters", parameters);
httppost.setentity(new stringentity(requestbody.tostring()));
// 4. 发送请求并处理响应
try (closeablehttpresponse response = httpclient.execute(httppost)) {
httpentity entity = response.getentity();
if (entity != null) {
string result = entityutils.tostring(entity);
// 5. 解析响应
jsonobject jsonresponse = new jsonobject(result);
return jsonresponse.getjsonobject("output")
.getstring("text");
}
}
}
return "未收到有效响应";
}
}3. 关键配置说明
模型选择(根据需求替换):
qwen-turbo:高速版(推荐常规使用)qwen-plus:增强版(适合复杂任务)qwen-max:最强能力版
流式响应:如需实时流式输出,添加:
httppost.setheader("x-dashscope-sse", "enable");安全建议:api key应通过环境变量传递:
# 设置环境变量(linux/macos) export dashscope_api_key=your_api_key # windows set dashscope_api_key=your_api_key
4. 响应处理示例
成功响应结构:
{
"output": {
"text": "量子计算是一种利用量子力学原理...",
"finish_reason": "stop"
},
"usage": {
"input_tokens": 10,
"output_tokens": 210
}
}5. 高级功能实现
流式输出处理:
// 添加流式支持
httppost.setheader("x-dashscope-sse", "enable");
// 处理流式响应
inputstream content = entity.getcontent();
try (bufferedreader reader = new bufferedreader(new inputstreamreader(content))) {
string line;
while ((line = reader.readline()) != null) {
if (line.startswith("data: ")) {
string jsonstr = line.substring(6);
jsonobject data = new jsonobject(jsonstr);
if (!data.has("output")) continue;
system.out.print(data.getjsonobject("output")
.getstring("text"));
}
}
}异常处理:
if (response.getstatusline().getstatuscode() != 200) {
string errorbody = entityutils.tostring(entity);
throw new runtimeexception("api调用失败: " + errorbody);
}常见问题解决
- 401错误:检查api key是否正确且未过期
- 400错误:验证请求体json格式是否正确
- 限流错误429:降低请求频率或联系阿里云扩容
- 超时问题:增加超时设置:
requestconfig config = requestconfig.custom()
.setconnecttimeout(30000)
.setsockettimeout(60000)
.build();
httppost.setconfig(config);到此这篇关于java调用通义千问api的详细步骤的文章就介绍到这了,更多相关java调用通义千问api内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论