模拟 Form 表单向微信公众平台上传图片永久素材

最近做了一个功能:实现将用户在平台的图片上传到用户自己的公众号。我这边实现是开发一个工具型的微信第三方平台,用户将自己的微信公众号对平台授权即可将在平台制作的图片上传到微信公众号。

新增永久素材时,微信指定使用 POST 请求,以 FORM 表单方式上传一个图片,因此需要模拟 form 表单发送请求,以下为主要实现:

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
String url = String.format("https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=%s&type=%s",
accessToken, type.getDesc());
HttpsURLConnection con = (HttpsURLConnection) new URL(url).openConnection();
// 以Post方式提交表单,默认get方式
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false); // post方式不能使用缓存
// 设置请求头信息
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
// 设置边界
String boundary = "----------" + System.currentTimeMillis();
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
// 请求正文信息
// 第一部分:表头信息
String sb = "--" +
boundary +
"\r\n" +
"Content-Disposition: form-data;name=\"media\";filename=\"" + filename + "\"\r\n" +
"Content-Type:application/octet-stream\r\n\r\n";
byte[] head = sb.getBytes("utf-8");
// 获得输出流
try (OutputStream out = new DataOutputStream(con.getOutputStream())) {
// 输出表头
out.write(head);
// 文件正文部分
// 把文件已流文件的方式 推入到url中
byte[] bufferOut = new byte[1024];
int bytes;
while ((bytes = is.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
// 结尾部分
byte[] foot = ("\r\n--" + boundary + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
out.write(foot);
out.flush();
}
// 定义BufferedReader输入流来读取URL的响应
String result;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
StringBuilder buffer = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
result = buffer.toString();
}

模拟 Form 表单向微信公众平台上传图片永久素材
https://blog.yohlj.cn/posts/616af239/
作者
Enoch
发布于
2017年12月29日
许可协议