java 调用 deepseek
时间: 2025-02-08 13:03:10 浏览: 153
### 如何在 Java 中调用 DeepSeek API
为了实现 Java 应用程序与 DeepSeek API 的交互,可以遵循以下方法:
#### 准备工作
确保已经获取了用于访问 DeepSeek API 所需的 API Key,并妥善保管该密钥[^3]。
#### 添加依赖项
对于基于 Spring Boot 的项目,在 `pom.xml` 文件中加入必要的 HTTP 客户端库支持。通常推荐使用 Apache HttpClient 或 OkHttp 这样的成熟方案来发起请求[^2]。
```xml
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.1</version>
</dependency>
```
#### 编写服务类
创建一个新的 Service 类用来封装向 DeepSeek 发送请求的具体逻辑。这里展示了一个简单的 GET 请求例子作为示范用途。
```java
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
public class DeepSeekService {
private static final String BASE_URL = "https://api.deepseek.com/v1";
public String fetchData(String endpoint, Map<String, Object> params) throws Exception {
StringBuilder urlBuilder = new StringBuilder(BASE_URL).append(endpoint);
try (CloseableHttpClient client = HttpClients.createDefault()) {
URIBuilder uriBuilder = new URIBuilder(urlBuilder.toString());
if(params != null && !params.isEmpty()){
for(Map.Entry<String,Object> entry : params.entrySet()){
uriBuilder.addParameter(entry.getKey(),entry.getValue().toString());
}
}
HttpGet request = new HttpGet(uriBuilder.build());
// 设置头部信息,特别是 Authorization 头部携带 API 密钥
request.setHeader("Authorization", "Bearer YOUR_API_KEY");
try(CloseableHttpResponse response = client.execute(request)){
int statusCode = response.getCode();
if(statusCode >= 200 && statusCode < 300){
return EntityUtils.toString(response.getEntity(),"UTF-8");
}else{
throw new RuntimeException("Failed to fetch data from server.");
}
}
}
}
}
```
请注意替换上述代码中的 `"YOUR_API_KEY"` 占位符为实际获得的有效 API Key 值。
阅读全文
相关推荐


















