java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java调用通义千问API

Java调用通义千问API的详细步骤

作者:别掉进我的异常

这篇文章主要介绍了在Java中接入通义千问API的步骤,包括获取APIKey、添加依赖、配置模型和流式响应等,并提供了响应处理和高级功能实现示例,以及常见问题解决方案,需要的朋友可以参考下

要在Java中接入通义千问API,请按以下步骤操作:

1. 准备工作

<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. 关键配置说明

模型选择(根据需求替换):

流式响应:如需实时流式输出,添加:

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);
}

常见问题解决

  1. 401错误:检查API Key是否正确且未过期
  2. 400错误:验证请求体JSON格式是否正确
  3. 限流错误429:降低请求频率或联系阿里云扩容
  4. 超时问题:增加超时设置:
RequestConfig config = RequestConfig.custom()
    .setConnectTimeout(30000)
    .setSocketTimeout(60000)
    .build();
httpPost.setConfig(config);

到此这篇关于Java调用通义千问API的详细步骤的文章就介绍到这了,更多相关Java调用通义千问API内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文