获取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内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论