Java 调用示例
本页面提供 Java 调用 51API 的完整示例。
环境准备
添加依赖
xml
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.12.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
groovy
implementation 'com.squareup.okhttp3:okhttp:4.12.0'
implementation 'com.google.code.gson:gson:2.10.1'1
2
2
kotlin
implementation("com.squareup.okhttp3:okhttp:4.12.0")
implementation("com.google.code.gson:gson:2.10.1")1
2
2
基础调用示例
使用 OkHttp
java
import okhttp3.*;
import java.io.IOException;
public class SimpleChat {
private static final String API_KEY = System.getenv("NEWAPI_API_KEY");
private static final String API_URL = "https://www.51api.org/v1/chat/completions";
public static void main(String[] args) throws IOException {
OkHttpClient client = new OkHttpClient();
// 构建请求体
String jsonBody = """
{
"model": "gpt-4o",
"messages": [
{"role": "system", "content": "你是一个有帮助的助手。"},
{"role": "user", "content": "你好!"}
]
}
""";
MediaType JSON = MediaType.get("application/json; charset=utf-8");
RequestBody body = RequestBody.create(jsonBody, JSON);
// 构建请求
Request request = new Request.Builder()
.url(API_URL)
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", "Bearer " + API_KEY)
.post(body)
.build();
// 发送请求
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful() && response.body() != null) {
System.out.println(response.body().string());
} else {
System.err.println("请求失败: " + response.code());
}
}
}
}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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
解析响应
使用 Gson 解析 JSON 响应:
java
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import okhttp3.*;
import java.io.IOException;
public class ParseResponse {
private static final String API_KEY = System.getenv("NEWAPI_API_KEY");
private static final String API_URL = "https://www.51api.org/v1/chat/completions";
private static final Gson gson = new Gson();
public static String chat(String message) throws IOException {
OkHttpClient client = new OkHttpClient();
// 构建请求
JsonObject payload = new JsonObject();
payload.addProperty("model", "gpt-4o");
JsonArray messages = new JsonArray();
JsonObject userMessage = new JsonObject();
userMessage.addProperty("role", "user");
userMessage.addProperty("content", message);
messages.add(userMessage);
payload.add("messages", messages);
MediaType JSON = MediaType.get("application/json; charset=utf-8");
RequestBody body = RequestBody.create(payload.toString(), JSON);
Request request = new Request.Builder()
.url(API_URL)
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", "Bearer " + API_KEY)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful() && response.body() != null) {
String responseBody = response.body().string();
// 解析响应
JsonObject jsonResponse = gson.fromJson(responseBody, JsonObject.class);
JsonArray choices = jsonResponse.getAsJsonArray("choices");
JsonObject firstChoice = choices.get(0).getAsJsonObject();
JsonObject messageObj = firstChoice.getAsJsonObject("message");
return messageObj.get("content").getAsString();
} else {
throw new IOException("请求失败: " + response.code());
}
}
}
public static void main(String[] args) {
try {
String reply = chat("你好,请介绍一下你自己");
System.out.println("AI: " + reply);
} catch (IOException e) {
e.printStackTrace();
}
}
}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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
流式响应
java
import okhttp3.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
public class StreamChat {
private static final String API_KEY = System.getenv("NEWAPI_API_KEY");
private static final String API_URL = "https://www.51api.org/v1/chat/completions";
private static final Gson gson = new Gson();
public static void main(String[] args) throws IOException {
OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(60, java.util.concurrent.TimeUnit.SECONDS)
.build();
String jsonBody = """
{
"model": "gpt-4o",
"messages": [
{"role": "user", "content": "讲一个简短的故事"}
],
"stream": true
}
""";
MediaType JSON = MediaType.get("application/json; charset=utf-8");
RequestBody body = RequestBody.create(jsonBody, JSON);
Request request = new Request.Builder()
.url(API_URL)
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", "Bearer " + API_KEY)
.post(body)
.build();
System.out.print("AI: ");
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
System.err.println("请求失败: " + response.code());
return;
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(response.body().byteStream())
);
String line;
while ((line = reader.readLine()) != null) {
if (line.isEmpty()) continue;
if (line.startsWith("data:")) {
String data = line.substring(5).trim();
if (data.equals("[DONE]")) {
break;
}
try {
JsonObject chunk = gson.fromJson(data, JsonObject.class);
JsonObject delta = chunk.getAsJsonArray("choices")
.get(0).getAsJsonObject()
.getAsJsonObject("delta");
if (delta != null && delta.has("content")) {
String content = delta.get("content").getAsString();
System.out.print(content);
}
} catch (Exception e) {
// 忽略解析错误
}
}
}
System.out.println();
}
}
}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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
封装工具类
将 API 调用封装为可复用的工具类:
java
import okhttp3.*;
import com.google.gson.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class Api51Client {
private final String apiKey;
private final String baseUrl;
private final OkHttpClient client;
private final Gson gson;
public Api51Client(String apiKey) {
this(apiKey, "https://www.51api.org/v1");
}
public Api51Client(String apiKey, String baseUrl) {
this.apiKey = apiKey;
this.baseUrl = baseUrl;
this.gson = new Gson();
this.client = new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(120, TimeUnit.SECONDS)
.build();
}
/**
* 发送聊天请求
*/
public String chat(String model, List<Message> messages) throws IOException {
JsonObject payload = new JsonObject();
payload.addProperty("model", model);
JsonArray messagesArray = new JsonArray();
for (Message msg : messages) {
JsonObject msgObj = new JsonObject();
msgObj.addProperty("role", msg.role);
msgObj.addProperty("content", msg.content);
messagesArray.add(msgObj);
}
payload.add("messages", messagesArray);
MediaType JSON = MediaType.get("application/json; charset=utf-8");
RequestBody body = RequestBody.create(payload.toString(), JSON);
Request request = new Request.Builder()
.url(baseUrl + "/chat/completions")
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", "Bearer " + apiKey)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException("API 请求失败: " + response.code());
}
String responseBody = response.body().string();
JsonObject jsonResponse = gson.fromJson(responseBody, JsonObject.class);
return jsonResponse.getAsJsonArray("choices")
.get(0).getAsJsonObject()
.getAsJsonObject("message")
.get("content").getAsString();
}
}
/**
* 简单聊天(单条消息)
*/
public String chat(String model, String message) throws IOException {
List<Message> messages = new ArrayList<>();
messages.add(new Message("user", message));
return chat(model, messages);
}
/**
* 消息类
*/
public static class Message {
public String role;
public String content;
public Message(String role, String content) {
this.role = role;
this.content = content;
}
}
// 使用示例
public static void main(String[] args) {
String apiKey = System.getenv("NEWAPI_API_KEY");
Api51Client api = new Api51Client(apiKey);
try {
String reply = api.chat("gpt-4o", "你好!");
System.out.println("AI: " + reply);
} catch (IOException e) {
e.printStackTrace();
}
}
}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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
常见问题
连接超时
增加超时时间设置:
java
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(300, TimeUnit.SECONDS) // DeepSearch 模型需要更长时间
.build();1
2
3
4
2
3
4
SSL 证书问题
如果遇到 SSL 问题,确保 JDK 版本较新(推荐 JDK 11+)。
其他问题
查看 完整常见问题
