最近做了一个功能:实现将用户在平台的图片上传到用户自己的公众号。我这边实现是开发一个工具型的微信第三方平台,用户将自己的微信公众号对平台授权即可将在平台制作的图片上传到微信公众号。
新增永久素材时,微信指定使用 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();
con.setRequestMethod("POST"); con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false);
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); 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(); }
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(); }
|