当前位置: 代码网 > it编程>编程语言>Java > Java调用通义千问API的详细步骤

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

2026年03月30日 Java 我要评论
要在java中接入通义千问api,请按以下步骤操作:1. 准备工作获取api key:登录阿里云dashscope控制台创建api key添加依赖:在pom.xml中添加apache httpclie

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

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

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

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

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com