Java 版 DeepSeek API 调用的小白详细教程
「Java版的DeepSeek API 调用笔记」,点击链接即可保存。
链接:https://pan.quark.cn/s/f4d1d30f19fe
「2025最新大模型全套资料及DeepSeek从入门到精通」
链接: https://pan.baidu.com/s/1NR1eJH9hEQeSA6hVUrJMKg?pwd=pcwq 提取码: pcwq
B站视频及源码获取:Java 调用AI 大模型 DeepSeek API 的小白详细教程_哔哩哔哩_bilibili
本案例为以 Java为例的调用 DeepSeek API 的小白入门级详细教程
步骤
- 先注册并登录 DeepSeek 官网:DeepSeek
- 手机号+验证码注册或登录即可
- 创建 API KEY
- 注意保存,写代码时必须提供的
- 打开 Pycharm 创建工程 并安装 OpenAI 库
- 编写代码发送请求调用,获取响应结果并打印
注册并登录官网
点击右上角 API 开放平台,如果没有登陆则会自动跳转至登录或注册页面
输入手机号后,点击发送验证码,勾选下面复选框,输入验证码即可登录。
创建 API Key
登录成功后,进入 API 开发平台后,默认会进入用量信息页,在这里可以看到自己的余额,第一次注册,平台会赠送10元用于购买 tokens。
点击左边菜单 API keys ,然后点击 创建 API KEY 进行创建
点击 创建按钮 后,弹出框中命名
点击 创建 按钮后,弹出下面的生成 key 的提示框,一定要点击复制按钮进行复制并保存
到此创建 API key 就完成了。注意:找个文本把刚复制的key 保存好
参考文档编写代码
点击左边 接口文档 菜单
或直接访问https://api-docs.deepseek.com/zh-cn/,进入 Deep Seek API 文档页面
这里有示例代码,直接可以复制到 Idea 中修改即可
应用小案例
视频:DeepSeek API 的 Python 调用小白详细教程_哔哩哔哩_bilibili
案例步骤:
- 查看请求体格式和响应格式
- 配置 pom.xml 中依赖
- 在 resources 下新建配置文件 config.properties
- 编写代码
- 加载配置文件,读取 key 和 url
- 设计请求体类和响应体类
- 使用 HttpClient 发送请求体
- 获取响应,封装到响应体中
- 动态逐个打印输出
首先在官网 API 了解数据格式
请求体数据格式
{
"messages": [
{
"content": "You are a helpful assistant",
"role": "system"
},
{
"content": "Hi",
"role": "user"
}
],
"model": "deepseek-chat",
"frequency_penalty": 0,
"max_tokens": 2048,
"presence_penalty": 0,
"response_format": {
"type": "text"
},
"stop": null,
"stream": false,
"stream_options": null,
"temperature": 1,
"top_p": 1,
"tools": null,
"tool_choice": "none",
"logprobs": false,
"top_logprobs": null
}
响应体数据格式
{
"id": "e7b8253a-f657-45d3-adbb-4c95435e6707",
"object": "chat.completion",
"created": 1740236670,
"model": "deepseek-chat",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Hello! How can I assist you today? 😊"
},
"logprobs": null,
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 9,
"completion_tokens": 11,
"total_tokens": 20,
"prompt_tokens_details": {
"cached_tokens": 0
},
"prompt_cache_hit_tokens": 0,
"prompt_cache_miss_tokens": 9
},
"system_fingerprint": "fp_3a5770e1b4_prod"
}
配置 pom.xml 中依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wdzl</groupId>
<artifactId>deepseek</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.2.1</version>
</dependency>
<!-- 如果使用Gson解析JSON -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>
</dependencies>
</project>
配置文件 config.properties
key=sk-8b8b2a6595854f2ba01be5a1e10fa326
url=https://api.deepseek.com/chat/completions
加载配置文件
读取 key 和 url
private static String API_KEY;
private static String API_URL;
static {
Properties properties = new Properties();
try {
InputStream is = DeepSeekClient.class.getResourceAsStream("/config.properties");
properties.load(is);
API_KEY = properties.getProperty("key");
API_URL = properties.getProperty("url");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
内部类
消息类 Message
// 内部类定义请求/响应结构
static class Message {
private String role;
private String content;
public Message(String role, String content) {
this.role = role;
this.content = content;
}
public String getContent() {
return content;
}
}
请求体类
/**
* 请求体的数据内部结构,用于构建请求 JSON
*/
static class ChatRequest {
private String model;
private List<Message> messages;
private double temperature;
private int max_tokens;
public ChatRequest(String model, List<Message> messages, double temperature, int max_tokens) {
this.model = model;
this.messages = messages;
this.temperature = temperature;
this.max_tokens = max_tokens;
}
}
响应体类
/**
* 按着响应的JSON格式来设计响应体
* 用来封装响应体字符串
*/
static class ChatResponse {
private List<Choice> choices;
public List<Choice> getChoices() {
return choices;
}
static class Choice {
private Message message;
public Message getMessage() {
return message;
}
}
}
发送请求的方法
ChatRequest requestBody) {
HttpClient client = HttpClient.newHttpClient();
Gson gson = new Gson();
//将 ChatRequest 对象中封装的数据转为 JSON 格式
String requestBodyJson = gson.toJson(requestBody);
// System.out.println("请求体:");
// System.out.println(requestBodyJson);
try {
//构建请求对象 并指定请求头内容格式及身份验证的key
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(API_URL))
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + API_KEY)
//将JSON格式的字符串封装为 BodyPublishers 对象
.POST(BodyPublishers.ofString(requestBodyJson))
.build(); //构建请求对象
System.out.println(">>>已提交问题,正在思考中....");
// 发送请求并获取响应对象
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
//如果响应状态码为成功 200
if (response.statusCode() == 200) {
// System.out.println("响应体:");
// System.out.println(response.body());
// 解析响应 把响应体中的json字符串转为 ChatResponse 对象
ChatResponse chatResponse = gson.fromJson(response.body(), ChatResponse.class);
//按 JSON 格式的方式 从自定义的ChatResponse 对象中逐级取出最终的响应对象
return chatResponse.getChoices().get(0).getMessage().getContent();
} else {
return "请求失败,状态码: " + response.statusCode() + ", 响应: " + response.body();
}
} catch (Exception e) {
e.printStackTrace();
return "请求异常: " + e.getMessage();
}
}
提问问题及打印响应
public static void ask(String content){
// 创建消息列表
List<Message> messages = new ArrayList<>();
messages.add(new Message("user", content));
// 构建请求体
ChatRequest requestBody = new ChatRequest(
"deepseek-chat", // 模型名称,根据文档调整
messages,
0.7, // temperature
1000 // max_tokens
);
System.out.println(">>>正在提交问题...");
long startTime = System.currentTimeMillis();
// 发送请求
String response = sendRequest(requestBody);
long endTime = System.currentTimeMillis();
System.out.println("思考用时:"+(endTime-startTime)/1000+"秒");
// System.out.println("响应内容: " + response);
TypewriterEffect.printWord(response,20);
}
调用测试
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = "";
System.out.println("*** 我是 DeepSeek ,很高兴见到您 ****");
while(true){
System.out.println("---请说您问题:---");
String question = scanner.next();
if("bye".equals(question)){
break;
}
ask(question);
System.out.println();
}
System.out.println("拜拜,欢迎下次使用!");
}
逐字打印
package com.util;
import java.util.Random;
public class TypewriterEffect {
public static void printWord(String text,int delay) {
for (int i = 0; i < text.length(); i++) {
// 打印单个字符
System.out.print(text.charAt(i));
// 立即刷新输出缓冲区
// System.out.flush();
try {
// 控制打印速度(单位:毫秒)
Thread.sleep(delay); // 200ms的延迟,可根据需要调整
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.err.println("打印被中断");
return;
}
}
// 打印完成后换行
System.out.println();
}
public static void main(String[] args) {
String message = "Hello, World! 这是一个Java实现的逐字打印效果示例。这是一个Java实现的逐字打印效果示例";
printWord(message,50);
}
}