-
Notifications
You must be signed in to change notification settings - Fork 142
/
PostObjectDemo.java
138 lines (133 loc) · 5.89 KB
/
PostObjectDemo.java
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
package com.qcloud.cos.demo;
import com.qcloud.cos.auth.COSSigner;
import com.qcloud.cos.utils.VersionInfoUtils;
import org.apache.commons.codec.binary.Base64;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PostObjectDemo {
public static void main(String[] args) throws Exception {
postObjectUploadDemo();
}
private static void postObjectUploadDemo() throws Exception {
String bucketName = "mybucket-12500000000";
String endpoint = "cos.ap-guangzhou.myqcloud.com";
String key = "images/test.jpg";
String filename = "test.jpg";
String inputFilePath = "test.jpg";
String contentType = "image/jpeg";
String secretId = "AKIDXXXXXXXX";
String seretKey = "1A2Z3YYYYYYYYYY";
long startTimestamp = System.currentTimeMillis() / 1000;
long endTimestamp = startTimestamp + 30 * 60;
String endTimestampStr = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").
format(endTimestamp * 1000);
String keyTime = startTimestamp + ";" + endTimestamp;
String boundary = "----WebKitFormBoundaryZBPbaoYE2gqeB21N";
// 设置表单的body字段值
Map<String, String> formFields = new HashMap<>();
formFields.put("q-sign-algorithm", "sha1");
formFields.put("key", key);
formFields.put("q-ak", secretId);
formFields.put("q-key-time", keyTime);
// 构造policy,参考文档: https://cloud.tencent.com/document/product/436/14690
String policy = "{\n" +
" \"expiration\": \"" + endTimestampStr + "\",\n" +
" \"conditions\": [\n" +
" { \"bucket\": \"" + bucketName + "\" },\n" +
" { \"q-sign-algorithm\": \"sha1\" },\n" +
" { \"q-ak\": \"" + secretId + "\" },\n" +
" { \"q-sign-time\":\"" + keyTime + "\" }\n" +
" ]\n" +
"}";
// policy需要base64后算放入表单中
String encodedPolicy = new String(Base64.encodeBase64(policy.getBytes()));
// 设置policy
formFields.put("policy", encodedPolicy);
// 根据编码后的policy和secretKey计算签名
COSSigner cosSigner = new COSSigner();
String signature = cosSigner.buildPostObjectSignature(seretKey,
keyTime, policy);
// 设置签名
formFields.put("q-signature", signature);
// 根据以上表单参数,构造最开始的body部分
String formBody = buildPostObjectBody(boundary, formFields,
filename, contentType);
HttpURLConnection conn = null;
try {
String urlStr = "http://" + bucketName + "." + endpoint;
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("User-Agent", VersionInfoUtils.getUserAgent());
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStream out = new DataOutputStream(conn.getOutputStream());
// 写入表单的最开始部分
out.write(formBody.getBytes());
// 将文件内容写入到输出流中
File file = new File(inputFilePath);
DataInputStream in = new DataInputStream(new FileInputStream(file));
int readBytes;
byte[] bytes = new byte[4096];
while ((readBytes = in.read(bytes)) != -1) {
out.write(bytes, 0, readBytes);
}
in.close();
// 添加最后一个分割符,行首和行尾都是--
byte[] endData = ("\r\n--" + boundary + "--\r\n").getBytes();
out.write(endData);
out.flush();
out.close();
// 读取响应头部
for (Map.Entry<String, List<String>> entries : conn.getHeaderFields().entrySet()) {
String values = "";
for (String value : entries.getValue()) {
values += value + ",";
}
if(entries.getKey() == null) {
System.out.println("reponse line:" + values );
} else {
System.out.println(entries.getKey() + ":" + values );
}
}
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
private static String buildPostObjectBody(String boundary, Map<String, String> formFields,
String filename, String contentType) {
StringBuffer stringBuffer = new StringBuffer();
for(Map.Entry entry: formFields.entrySet()) {
// 添加boundary行,行首以--开头
stringBuffer.append("--").append(boundary).append("\r\n");
// 字段名
stringBuffer.append("Content-Disposition: form-data; name=\""
+ entry.getKey() + "\"\r\n\r\n");
// 字段值
stringBuffer.append(entry.getValue() + "\r\n");
}
// 添加boundary行,行首以--开头
stringBuffer.append("--").append(boundary).append("\r\n");
// 文件名
stringBuffer.append("Content-Disposition: form-data; name=\"file\"; "
+ "filename=\"" + filename + "\"\r\n");
// 文件类型
stringBuffer.append("Content-Type: " + contentType + "\r\n\r\n");
return stringBuffer.toString();
}
}