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

常见问题解决

  1. 401错误:检查API Key是否正确且未过期

  2. 400错误:验证请求体JSON格式是否正确

  3. 限流错误429:降低请求频率或联系阿里云扩容

  4. 超时问题:增加超时设置:

    RequestConfig config = RequestConfig.custom()
        .setConnectTimeout(30000)
        .setSocketTimeout(60000)
        .build();
    httpPost.setConfig(config);

最新API文档参考:阿里云DashScope官方文档

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐