一、SDK引入
pom.xml中引入相关依赖
xml
<!-- https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dashscope-sdk-java</artifactId>
<version>2.19.1</version>
</dependency>
代码
java
import java.util.Arrays;
import java.lang.System;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
/**
* 阿里云通义千问官方SDK调用示例
* 相比原生HTTP,SDK更简洁、更安全、参数更规范
*/
public class SdkAiInvoke {
/**
* 调用通义千问AI接口的核心方法
* @return AI返回的结果对象
* @throws ApiException API调用异常
* @throws NoApiKeyException 未提供API Key异常
* @throws InputRequiredException 缺少必填参数异常
*/
public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
// 1. 创建AI对话生成器对象(SDK核心类)
Generation gen = new Generation();
// 2. 构建系统消息:定义AI的角色/行为规则
Message systemMsg = Message.builder()
.role(Role.SYSTEM.getValue()) // 角色:system(系统设定)
.content("You are a helpful assistant.") // AI的行为指令
.build();
// 3. 构建用户消息:实际提问内容
Message userMsg = Message.builder()
.role(Role.USER.getValue()) // 角色:user(用户)
.content("你是谁?") // 用户提问
.build();
// 4. 构建请求参数(SDK封装,无需手动拼JSON)
GenerationParam param = GenerationParam.builder()
// 填写你的阿里云API Key
.apiKey({{这里填充你自己 申请的API_KEY}})
// 指定使用的AI模型,可在阿里云控制台更换
.model("qwen-plus")
// 传入对话消息列表(系统+用户)
.messages(Arrays.asList(systemMsg, userMsg))
// 指定返回格式为MESSAGE结构,方便解析
.resultFormat(GenerationParam.ResultFormat.MESSAGE)
.build();
// 5. 发送请求并返回结果
return gen.call(param);
}
/**
* 程序入口:执行调用并打印结果
*/
public static void main(String[] args) {
try {
// 调用AI接口获取结果
GenerationResult result = callWithMessage();
// 将结果转为JSON格式输出控制台
System.out.println(JsonUtils.toJson(result));
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
// 捕获并输出异常信息
System.err.println("An error occurred while calling the generation service: " + e.getMessage());
}
// 程序正常退出
System.exit(0);
}
}

二、HTTP 调用
java
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
/**
* Java 调用阿里云通义千问AI接口
*/
public class HttpAiInvoke {
public static void main(String[] args) {
// 通义千问API地址
String url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
// 请求头:鉴权 + JSON格式
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Bearer " + {{这里填充你自己 申请的API_KEY}};
headers.put("Content-Type", "application/json");
// 构建请求体
JSONObject requestBody = new JSONObject();
requestBody.put("model", "qwen-plus"); // 指定AI模型
// 构造对话消息
JSONObject input = new JSONObject();
JSONObject[] messages = new JSONObject[2];
// 系统角色:定义AI行为
JSONObject systemMessage = new JSONObject();
systemMessage.put("role", "system");
systemMessage.put("content", "You are a helpful assistant.");
messages[0] = systemMessage;
// 用户提问
JSONObject userMessage = new JSONObject();
userMessage.put("role", "user");
userMessage.put("content", "你是谁?");
messages[1] = userMessage;
input.put("messages", messages);
requestBody.put("input", input);
// 响应参数设置
JSONObject parameters = new JSONObject();
parameters.put("result_format", "message");
requestBody.put("parameters", parameters);
// 发送POST请求
HttpResponse response = HttpRequest.post(url)
.addHeaders(headers)
.body(requestBody.toString())
.execute();
// 处理响应结果
if (response.isOk()) {
System.out.println("请求成功,响应内容:");
System.out.println(response.body());
} else {
System.out.println("请求失败,状态码:" + response.getStatus());
System.out.println("响应内容:" + response.body());
}
}
}
结果展示

三、SpringAI
引入依赖
xml
<dependency>
<groupId>com.alibaba.cloud.ai</groupId>
<artifactId>spring-ai-alibaba-starter</artifactId>
<version>1.0.0-M6.1</version>
</dependency>
配置文件
yaml
spring:
#springAI配置
application:
name: spring-ai-alibaba-qwq-chat-client-example
ai:
dashscope:
api-key: {{这里填充你自己 申请的API_KEY}}
chat:
options:
model: qwen-plus
java
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import jakarta.annotation.Resource;
// 取消注释即可在 SpringBoot 项目启动时执行
@Component
public class SpringAiAiInvoke implements CommandLineRunner {
// 注入阿里云通义千问 AI 模型(Spring AI 自动装配)
@Resource
private ChatModel dashscopeChatModel;
/**
* SpringBoot 项目启动后自动执行的方法
*/
@Override
public void run(String... args) throws Exception {
// 向 AI 发送提问:你好
// call():调用 AI 接口;getResult():获取响应结果;getOutput():获取 AI 回复消息
AssistantMessage output = dashscopeChatModel.call(new Prompt("你好"))
.getResult()
.getOutput();
// 打印 AI 返回的回答内容
System.out.println(output.getText());
}
}
四、langchain4j
首先引入依赖
xml
<!-- https://mvnrepository.com/artifact/dev.langchain4j/langchain4j-community-dashscope -->
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-community-dashscope</artifactId>
<version>1.0.0-beta2</version>
</dependency>
java
import dev.langchain4j.community.model.dashscope.QwenChatModel;
import dev.langchain4j.model.chat.ChatLanguageModel;
public class LangChainAiInvoke {
public static void main(String[] args) {
ChatLanguageModel qwenModel = QwenChatModel.builder()
.apiKey({{这里填充你自己 申请的API_KEY}})
.modelName("qwen-max")
.build();
String answer = qwenModel.chat("我是程序员");
System.out.println(answer);
}
}
