Request.java
11.3 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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
package com.qcloud.Common;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import com.qcloud.Utilities.MD5;
/**
* @brief 请求调用类
* @author robinslsun
*/
public class Request {
protected static String requestUrl = "";
protected static String rawResponse = "";
protected static String version = "SDK_JAVA_1.3";
protected static int timeOut = 1000;//设置连接主机的超时时间,单位:毫秒,可以根据实际需求合理更改 timeOut 的值。
public static String getRequestUrl() {
return requestUrl;
}
public static String getRawResponse() {
return rawResponse;
}
public static String generateUrl(TreeMap<String, Object> params,
String secretId, String secretKey, String requestMethod,
String requestHost, String requestPath) {
if (!params.containsKey("SecretId"))
params.put("SecretId", secretId);
if (!params.containsKey("Nonce"))
params.put("Nonce",
new Random().nextInt(Integer.MAX_VALUE));
if (!params.containsKey("Timestamp"))
params.put("Timestamp", System.currentTimeMillis() / 1000);
params.put("RequestClient", version);
String plainText = Sign.makeSignPlainText(params, requestMethod,
requestHost, requestPath);
try {
params.put("Signature", Sign.sign(plainText, secretKey));
} catch (Exception e) {
e.printStackTrace();
}
if (params.get("Action").toString().equals("MultipartUploadVodFile")) {
String url = "http://" + requestHost + requestPath;
url += Sign.buildParamStr1(params,requestMethod);
return url;
}
String url = "https://" + requestHost + requestPath;
if (requestMethod.equals("GET")) {
url += Sign.buildParamStr1(params,requestMethod);
}
return url;
}
public static String send(TreeMap<String, Object> params, String secretId,
String secretKey, String requestMethod, String requestHost,
String requestPath, String fileName) {
if (!params.containsKey("SecretId"))
params.put("SecretId", secretId);
if (!params.containsKey("Nonce"))
params.put("Nonce",
new Random().nextInt(Integer.MAX_VALUE));
if (!params.containsKey("Timestamp"))
params.put("Timestamp", System.currentTimeMillis() / 1000);
params.put("RequestClient", version);
params.remove("Signature");
String plainText = Sign.makeSignPlainText(params, requestMethod,
requestHost, requestPath);
try {
params.put("Signature", Sign.sign(plainText, secretKey));
} catch (Exception e) {
e.printStackTrace();
}
if (params.get("Action").toString().equals("MultipartUploadVodFile")) {
String url = "http://" + requestHost + requestPath;
return sendMultipartUploadVodFileRequest(url, params,
requestMethod, fileName);
}
String url = "https://" + requestHost + requestPath;
return sendRequest(url, params, requestMethod, fileName);
}
public static String sendRequest(String url,
Map<String, Object> requestParams, String requestMethod,
String fileName) {
String result = "";
BufferedReader in = null;
String paramStr = "";
for (String key : requestParams.keySet()) {
if (!paramStr.isEmpty()) {
paramStr += '&';
}
try {
paramStr += key + '='
+ URLEncoder.encode(requestParams.get(key).toString(),"utf-8");
} catch (UnsupportedEncodingException e) {
result = "{\"code\":-2300,\"location\":\"com.qcloud.Common.Request:129\",\"message\":\"api sdk throw exception! "
+ e.toString() + "\"}";
}
}
try {
if (requestMethod.equals("GET")) {
if (url.indexOf('?') > 0) {
url += '&' + paramStr;
} else {
url += '?' + paramStr;
}
}
requestUrl = url;
String BOUNDARY = "---------------------------"
+ MD5.stringToMD5(
String.valueOf(System.currentTimeMillis()))
.substring(0, 15);
URL realUrl = new URL(url);
URLConnection connection = null;
if (url.toLowerCase().startsWith("https")) {
HttpsURLConnection httpsConn = (HttpsURLConnection) realUrl
.openConnection();
httpsConn.setHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
connection = httpsConn;
} else {
connection = realUrl.openConnection();
}
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 设置链接主机超时时间
connection.setConnectTimeout(timeOut);
if (requestMethod.equals("POST")) {
((HttpURLConnection) connection).setRequestMethod("POST");
// 发送POST请求必须设置如下两行
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + BOUNDARY);
OutputStream out = new DataOutputStream(
connection.getOutputStream());
StringBuffer strBuf = new StringBuffer();
for (String key : requestParams.keySet()) {
strBuf.append("\r\n").append("--").append(BOUNDARY)
.append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\""
+ key + "\"\r\n\r\n");
strBuf.append(requestParams.get(key));
}
out.write(strBuf.toString().getBytes());
if (fileName != null) {
File file = new File(fileName);
String filename = file.getName();
String contentType = URLConnection.getFileNameMap()
.getContentTypeFor(fileName);
strBuf = new StringBuffer();
strBuf.append("\r\n").append("--").append(BOUNDARY)
.append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"entityFile\"; filename=\""
+ filename + "\"\r\n");
strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
out.write(strBuf.toString().getBytes());
DataInputStream ins = new DataInputStream(
new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = ins.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
ins.close();
}
byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
out.write(endData);
out.flush();
out.close();
}
// 建立实际的连接
connection.connect();
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
result = "{\"code\":-2700,\"location\":\"com.qcloud.Common.Request:225\",\"message\":\"api sdk throw exception! "
+ e.toString() + "\"}";
} finally {
// 使用finally块来关闭输入流
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
result = "{\"code\":-2800,\"location\":\"com.qcloud.Common.Request:234\",\"message\":\"api sdk throw exception! "
+ e2.toString() + "\"}";
}
}
rawResponse = result;
return result;
}
public static String sendMultipartUploadVodFileRequest(String url,
Map<String, Object> requestParams, String requestMethod,
String fileName) {
String result = "";
BufferedReader in = null;
String paramStr = "";
for (String key : requestParams.keySet()) {
if (!paramStr.isEmpty()) {
paramStr += '&';
}
try {
paramStr += key + '='
+ URLEncoder.encode(requestParams.get(key).toString(),"utf-8");
} catch (UnsupportedEncodingException e) {
result = "{\"code\":-2400,\"location\":\"com.qcloud.Common.Request:263\",\"message\":\"api sdk throw exception! "
+ e.toString() + "\"}";
}
}
try {
if (url.indexOf('?') > 0) {
url += '&' + paramStr;
} else {
url += '?' + paramStr;
}
System.out.println(url);
requestUrl = url;
// String BOUNDARY = "---------------------------" +
// MD5.stringToMD5(String.valueOf(System.currentTimeMillis())).substring(0,15);
URL realUrl = new URL(url);
URLConnection connection = null;
if (url.toLowerCase().startsWith("https")) {
HttpsURLConnection httpsConn = (HttpsURLConnection) realUrl
.openConnection();
httpsConn.setHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
connection = httpsConn;
} else {
connection = realUrl.openConnection();
}
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.setDoOutput(true);
connection.setDoInput(true);
// 设置链接主机超时时间
connection.setConnectTimeout(timeOut);
File file = new File(fileName);
long file_length = (Long) requestParams.get("fileSize");
OutputStream out = new DataOutputStream(
connection.getOutputStream());
DataInputStream ins = new DataInputStream(new FileInputStream(file));
int offset = ((Integer) requestParams.get("offset")).intValue();
int dataSize = ((Integer) requestParams.get("dataSize")).intValue();
if (offset >= file_length) {
return "{\"code\":-3001,\"location\":\"com.qcloud.Common.Request:303\",\"message\":\"api sdk throw exception! offset larger than the size of file\"}";
}
int skipBytes = ins.skipBytes(offset);
int page = dataSize / 1024;
int remainder = dataSize % 1024;
int bytes = 0;
byte[] bufferOut = new byte[1024];
byte[] bufferOut2 = new byte[remainder];
while (page != 0) {
if ((bytes = ins.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
page = page - 1;
}
if ((bytes = ins.read(bufferOut2)) != -1) {
out.write(bufferOut2, 0, bytes);
}
ins.close();
out.flush();
out.close();
// 建立实际的连接
connection.connect();
try {
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
} catch (Exception e) {
result = "{\"code\":-3002,\"location\":\"com.qcloud.Common.Request:331\",\"message\":\"api sdk throw exception! protocol doesn't support input or the character Encoding is not supported."
+ "details: " + e.toString() + "\"}";
if (in != null) {
in.close();
}
rawResponse = result;
return result;
}
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
result = "{\"code\":-3000,\"location\":\"com.qcloud.Common.Request:345\",\"message\":\"api sdk throw exception! "
+ e.toString() + "\"}";
} finally {
// 使用finally块来关闭输入流
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
result = "{\"code\":-3003,\"location\":\"com.qcloud.Common.Request:354\",\"message\":\"api sdk throw exception! "
+ e2.toString() + "\"}";
}
}
rawResponse = result;
return result;
}
}