Java调用通义千问API的详细步骤
更新时间:2026年03月30日 09:45:43 作者:别掉进我的异常
这篇文章主要介绍了在Java中接入通义千问API的步骤,包括获取APIKey、添加依赖、配置模型和流式响应等,并提供了响应处理和高级功能实现示例,以及常见问题解决方案,需要的朋友可以参考下
要在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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
idea没有services窗口、没有springboot启动项问题
这篇文章主要介绍了idea没有services窗口、没有springboot启动项问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2024-05-05
更简单更高效的Mybatis Plus最新代码生成器AutoGenerator
这篇文章主要为大家介绍了更简单更高效的Mybatis Plus最新代码生成器AutoGenerator使用详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-02-02


最新评论