获取API密钥首先,从DeepSeek平台获取API密钥,用于身份验证。
添加HTTP客户端依赖使用Java的HTTP客户端库(如Apache HttpClient或OkHttp)来发送HTTP请求。如果使用Maven,可以在pom.xml中添加依赖:、
1 | org.apache.httpcomponentshttpclient4.5.13com.squareup.okhttp3okhttp4.9.3 |
创建HTTP请求使用HTTP客户端库创建请求,设置请求头、URL和请求体
使用Apache HttpClient示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | 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_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示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | import okhttp3.*; import java.io.IOException; public class DeepSeekClient { 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内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!