Java調(diào)用通義千問(wèn)API的詳細(xì)步驟
要在Java中接入通義千問(wèn)API,請(qǐng)按以下步驟操作:
1. 準(zhǔn)備工作
- 獲取API Key:登錄阿里云DashScope控制臺(tái)創(chuàng)建API Key
- 添加依賴:在
pom.xml中添加Apache HttpClient和JSON庫(kù)依賴
<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 {
// 從環(huán)境變量獲取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("解釋一下量子計(jì)算");
System.out.println("API 響應(yīng):\n" + response);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String callQianwenAPI(String userInput) throws Exception {
// 1. 創(chuàng)建HTTP客戶端
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// 2. 構(gòu)建請(qǐng)求
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. 構(gòu)建請(qǐng)求體
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. 發(fā)送請(qǐng)求并處理響應(yīng)
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity);
// 5. 解析響應(yīng)
JSONObject jsonResponse = new JSONObject(result);
return jsonResponse.getJSONObject("output")
.getString("text");
}
}
}
return "未收到有效響應(yīng)";
}
}3. 關(guān)鍵配置說(shuō)明
模型選擇(根據(jù)需求替換):
qwen-turbo:高速版(推薦常規(guī)使用)qwen-plus:增強(qiáng)版(適合復(fù)雜任務(wù))qwen-max:最強(qiáng)能力版
流式響應(yīng):如需實(shí)時(shí)流式輸出,添加:
httpPost.setHeader("X-DashScope-SSE", "enable");安全建議:API Key應(yīng)通過(guò)環(huán)境變量傳遞:
# 設(shè)置環(huán)境變量(Linux/macOS) export DASHSCOPE_API_KEY=your_api_key # Windows set DASHSCOPE_API_KEY=your_api_key
4. 響應(yīng)處理示例
成功響應(yīng)結(jié)構(gòu):
{
"output": {
"text": "量子計(jì)算是一種利用量子力學(xué)原理...",
"finish_reason": "stop"
},
"usage": {
"input_tokens": 10,
"output_tokens": 210
}
}5. 高級(jí)功能實(shí)現(xiàn)
流式輸出處理:
// 添加流式支持
httpPost.setHeader("X-DashScope-SSE", "enable");
// 處理流式響應(yīng)
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調(diào)用失敗: " + errorBody);
}常見問(wèn)題解決
- 401錯(cuò)誤:檢查API Key是否正確且未過(guò)期
- 400錯(cuò)誤:驗(yàn)證請(qǐng)求體JSON格式是否正確
- 限流錯(cuò)誤429:降低請(qǐng)求頻率或聯(lián)系阿里云擴(kuò)容
- 超時(shí)問(wèn)題:增加超時(shí)設(shè)置:
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(30000)
.setSocketTimeout(60000)
.build();
httpPost.setConfig(config);到此這篇關(guān)于Java調(diào)用通義千問(wèn)API的詳細(xì)步驟的文章就介紹到這了,更多相關(guān)Java調(diào)用通義千問(wèn)API內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java中MapStruct映射處理器報(bào)錯(cuò)的問(wèn)題解決
MapStruct是一個(gè)強(qiáng)大的Java映射框架,它能夠在編譯時(shí)生成映射代碼,,本文主要介紹了Java中MapStruct映射處理器報(bào)錯(cuò)的問(wèn)題解決,具有一定的參考價(jià)值,感興趣的可以了解一下2024-03-03
Mybatis?Interceptor線程安全引發(fā)的bug問(wèn)題
這篇文章主要介紹了Mybatis?Interceptor線程安全引發(fā)的bug問(wèn)題及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02
Java?Swing實(shí)現(xiàn)自定義彈窗組件CusDialog(附源碼)
Swing 原生對(duì)話框 JDialog 和 JFrame 一樣,標(biāo)題欄是系統(tǒng)自帶的,樣式陳舊且無(wú)法自定義,下面我們就來(lái)看看如何通過(guò)Java Swing實(shí)現(xiàn)自定義彈窗組件CusDialog吧2026-05-05
Spring 異步執(zhí)行器(Executor)配置策略與命名實(shí)踐
這篇文章主要介紹了Spring 異步執(zhí)行器(Executor)配置策略與命名實(shí)踐,本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2026-02-02

