java post 库,【Java】POST简略

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

提交格式:

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--

示例代码

import java.io.*;

import .HttpURLConnection;

import .MalformedURLException;

import .ProtocolException;

import .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> keyValues = new HashMap<>();

private Map> 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> 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> 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("外链网址已屏蔽");

System.out.println(response);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值