<!-- 使用Apache HttpClient deepSeek -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
package com.ruoyi.system.controller;
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;
public class TestController {
private static final String API_URL = "https://api.deepseek.com/chat/completions";
private static final String API_KEY = "替换为实际API Key";
public static void main(String[] args) {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(API_URL);
httpPost.setHeader("Authorization", "Bearer " + API_KEY);
httpPost.setHeader("Content-Type", "application/json");
String jsonBody = "{" + "\"model\": \"deepseek-chat\"," + "\"messages\": [" + "{\"role\": \"system\", \"content\": \"你是一个Java技术专家\"}," + "{\"role\": \"user\", \"content\": \"如何用Java实现快速排序?\"}" + "]," + "\"stream\": false" + "}";
httpPost.setEntity(new StringEntity(jsonBody));
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity);
System.out.println("响应结果:" + result);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}