JAVA调用Deepseek的api完成基本对话简单代码示例
作者:菜菜-plus
这篇文章主要介绍了JAVA调用Deepseek的api完成基本对话的相关资料,文中详细讲解了如何获取DeepSeek API密钥、添加HTTP客户端依赖、创建HTTP请求并使用示例代码来对接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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!