Repository navigation
Expand file tree
/
Copy pathApiClient.java
More file actions
212 lines (186 loc) · 7.38 KB
/
Copy pathApiClient.java
File metadata and controls
212 lines (186 loc) · 7.38 KB
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
package com.example.wmchat2026;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
/**
* ApiClient
* 增强版:支持普通 POST/GET 请求、JSON POST 请求,以及 Multipart 文件上传
*/
public class ApiClient {
/**
* GET 请求(读取 JSON)
*/
public static JSONObject get(String urlStr) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(8000);
conn.setReadTimeout(8000);
return readResponse(conn);
}
/**
* POST 请求(用于普通表单 URL-encoded 数据)
*/
public static JSONObject post(String urlStr, String postData) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(8000);
conn.setReadTimeout(8000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(postData);
writer.flush();
writer.close();
os.close();
return readResponse(conn);
}
/**
* POST 请求(返回原始字符串,不解析 JSON)
* 用于调试服务器返回内容
*/
public static String postRaw(String urlStr, String postData) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(8000);
conn.setReadTimeout(8000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 写入请求数据
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(postData);
writer.flush();
writer.close();
os.close();
// 读取返回
int responseCode = conn.getResponseCode();
InputStream is = (responseCode == HttpURLConnection.HTTP_OK)
? conn.getInputStream()
: conn.getErrorStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
is.close();
conn.disconnect();
return sb.toString();
}
/**
* POST 请求(用于发送 JSON 数据)
*/
public static JSONObject postJson(String urlStr, String json) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(json);
writer.flush();
writer.close();
os.close();
return readResponse(conn);
}
/**
* Multipart 文件上传(用于发送语音文件)
* 对应后端 action=send_message,接收 $_FILES['audio']
*/
public static JSONObject uploadFile(String urlStr, HashMap<String, String> params, String fileKey, File file) throws Exception {
String boundary = "*****" + System.currentTimeMillis() + "*****";
String LINE_END = "\r\n";
String TWO_HYPHENS = "--";
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
// 1. 写入文本参数 (token, to 等)
if (params != null) {
for (String key : params.keySet()) {
dos.writeBytes(TWO_HYPHENS + boundary + LINE_END);
dos.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + LINE_END);
dos.writeBytes("Content-Type: text/plain; charset=UTF-8" + LINE_END);
dos.writeBytes(LINE_END);
dos.write(params.get(key).getBytes("UTF-8"));
dos.writeBytes(LINE_END);
}
}
// 2. 写入文件二进制流
if (file != null && file.exists()) {
dos.writeBytes(TWO_HYPHENS + boundary + LINE_END);
dos.writeBytes("Content-Disposition: form-data; name=\"" + fileKey + "\"; filename=\"" + file.getName() + "\"" + LINE_END);
dos.writeBytes("Content-Type: audio/wav" + LINE_END);
dos.writeBytes(LINE_END);
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[8192];
int count;
while ((count = fis.read(buffer)) != -1) {
dos.write(buffer, 0, count);
}
fis.close();
dos.writeBytes(LINE_END);
}
// 3. 结束 Multipart
dos.writeBytes(TWO_HYPHENS + boundary + TWO_HYPHENS + LINE_END);
dos.flush();
dos.close();
return readResponse(conn);
}
/**
* 读取 HTTP 响应并转为 JSONObject
*/
private static JSONObject readResponse(HttpURLConnection conn) throws Exception {
int responseCode = conn.getResponseCode();
InputStream is = (responseCode == HttpURLConnection.HTTP_OK) ? conn.getInputStream() : conn.getErrorStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
is.close();
conn.disconnect();
return new JSONObject(sb.toString());
}
/**
* URL 编码
*/
public static String encode(String s) {
try {
return URLEncoder.encode(s, "UTF-8");
} catch (Exception e) {
return s;
}
}
}