POST简略

简单描述:

post的数据在 request Payload 内, 因此,Request Headers 里面带有一个 boundary 属性,服务器收到 post 请求之后,通过 boundary 将参数从 Payload 中分离出来。

params = body.split(boundary)

唯一需要注意的是,CRLF(回车换行符)的使用。HTTP协议对CRLF的内容分割要求还是略严的。

Request Headers

Content-Type:multipart/form-data; boundary=----WebKitFormBoundarydKY7YrWhI3bdiNYz

Request Payload

--{boundary}
Content-Disposition: form-data; name="{name1}"

{value1}
--{boundary}
Content-Disposition: form-data; name="{name2}"

{value2}
--{boundary}
Content-Disposition: form-data; name="{file_name1}"; filename="xxx.png"
Content-Type: image/png

0x120x12...

--{boundary}--

示例说明

1
2
3
4
5
<form method="post" enctype="multipart/form-data">
<div><input type="checkbox" name="k1" checked value="1"/><label>1</label></div>
<div><input type="checkbox" name="k1" checked value="2"/><label>2</label></div>
<div><input type="file" name="pic"/></div>
</form>

提交格式:

headers

Content-Type:multipart/form-data; boundary=----WebKitFormBoundarydKY7YrWhI3bdiNYz

payload:

------WebKitFormBoundarydKY7YrWhI3bdiNYz
Content-Disposition: form-data; name="k1"

1
------WebKitFormBoundarydKY7YrWhI3bdiNYz
Content-Disposition: form-data; name="k2"

2
------WebKitFormBoundarydKY7YrWhI3bdiNYz
Content-Disposition: form-data; name="{file_name1}"; filename="xxx.png"
Content-Type: image/png

....(这里是图片字节).....

------WebKitFormBoundarydKY7YrWhI3bdiNYz--

示例代码

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
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Post {

private String BOUNDARY = "-------1234567890987654321";
private String CRLF = "\r\n";
private Map<String, List<String>> keyValues = new HashMap<>();
private Map<String, List<String>> pngs = new HashMap<>();

//添加字符串键值对
public void keyValue(String key, String value) {
if (!keyValues.containsKey(key)) {
keyValues.put(key, new ArrayList<>());
}
keyValues.get(key).add(value);
}

//添加png图片
public void png(String key, String pngFilePath) {
if (!pngs.containsKey(key)) {
pngs.put(key, new ArrayList<>());
}
pngs.get(key).add(pngFilePath);
}

public String post(String urlString) {
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.setReadTimeout(10000);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

OutputStream out = new DataOutputStream(connection.getOutputStream());

for (Map.Entry<String, List<String>> kv : keyValues.entrySet()) {
for (String value : kv.getValue()) {
String item = new StringBuilder("--").append(BOUNDARY).append(CRLF)
.append("Content-Disposition: form-data; name=").append(kv.getKey()).append(CRLF)
.append(CRLF)
.append(value).append(CRLF)
.toString();
out.write(item.getBytes());
}
}

//添加png图片
for (Map.Entry<String, List<String>> kv : pngs.entrySet()) {
for (String value : kv.getValue()) {
String item = new StringBuilder("--").append(BOUNDARY).append(CRLF)
.append("Content-Disposition: form-data; name=").append(kv.getKey()).append(";").append("filename=").append(value).append(CRLF)
.append("Content-Type: image/png").append(CRLF)
.append(CRLF)
.toString();
out.write(item.getBytes());

//写入文件内容
FileInputStream fileInputStream = new FileInputStream(value);
byte[] bytes = new byte[512];
int count;
while ((count = fileInputStream.read(bytes)) != -1) {
out.write(bytes, 0, count);
}
out.write(CRLF.getBytes());
}
}
out.write(("--" + BOUNDARY + "--" + CRLF).getBytes());//结尾

out.flush();
out.close();

StringBuffer response = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
response.append(line).append("\n");
}
reader.close();
return response.toString();

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}

public static void main(String[] args) throws IOException {

Post post = new Post();
post.keyValue("k1", "a");
post.keyValue("k2", "b");
post.png("pic", "/home/xe/Pictures/1.png");
post.png("pic", "/home/xe/Pictures/1.png");

String response = post.post("http://127.0.0.1:3000/upload");
System.out.println(response);
}
}