JAVA调用Deepseek的api完成基本对话简单代码示例,
分享于 点击 16914 次 点评:57
JAVA调用Deepseek的api完成基本对话简单代码示例,
获取API密钥首先,从DeepSeek平台获取API密钥,用于身份验证。
添加HTTP客户端依赖使用Java的HTTP客户端库(如Apache HttpClient或OkHttp)来发送HTTP请求。如果使用Maven,可以在pom.xml中添加依赖:、
<!-- Apache HttpClient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> <!-- OkHttp --> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.9.3</version> </dependency>
创建HTTP请求使用HTTP客户端库创建请求,设置请求头、URL和请求体
使用Apache HttpClient示例:
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 DeepSeekClient { private static final String API_URL = "https://api.deepseek.com/v1/your-endpoint"; private static final String API_KEY = "your-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 json = "{\"name\":\"tom\"}"; // 替换为实际请求体 httpPost.setEntity(new StringEntity(json)); 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(); } } }
使用OkHttp示例
import okhttp3.*; import java.io.IOException; public class DeepSeekClient { private static final String API_URL = "https://api.deepseek.com/v1/your-endpoint"; private static final String API_KEY = "your-api-key"; public static void main(String[] args) { OkHttpClient client = new OkHttpClient(); MediaType mediaType = MediaType.parse("application/json"); String json = "{\"name\":\"tom\"}"; // 替换为实际请求体 RequestBody body = RequestBody.create(mediaType, json); Request request = new Request.Builder() .url(API_URL) .post(body) .addHeader("Authorization", "Bearer " + API_KEY) .addHeader("Content-Type", "application/json") .build(); try (Response response = client.newCall(request).execute()) { if (response.isSuccessful() && response.body() != null) { System.out.println(response.body().string()); } } catch (IOException e) { e.printStackTrace(); } } }
通过以上步骤,你可以在Java中成功对接DeepSeek API,也可整合springboot,通过springboot发送向deepseek发送请求。
总结
到此这篇关于JAVA调用Deepseek的api完成基本对话的文章就介绍到这了,更多相关JAVA调用Deepseek的api内容请搜索3672js教程以前的文章或继续浏览下面的相关文章希望大家以后多多支持3672js教程!
您可能感兴趣的文章:- Java调用Deepseek实现项目代码审查
- Java调用DeepSeek API的最佳实践及详细代码示例
- Python使用Flask结合DeepSeek开发(实现代码)
- SpringBoot接入deepseek深度求索示例代码(jdk1.8)
- springboot接入deepseek深度求索代码示例(java版)
- 基于DeepSeek-Coder的跨文件代码补全实战教程
用户点评