微信官方给出的例子仅仅是使用curl上传的本地资源,以下提供了一种模拟的请求方式去在代码中上传
byte[] fileBytes = "your file bytes";
String filename = "your file name";
String accessToken = "your wx access token";
String type = "iamage";
URL url = new URL(String.format("https://api.weixin.qq.com/cgi-bin/media/upload?access_token=%s&type=%s", accessToken, type));
// 创建Http连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
// 消息请求头信息
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");
// 设置开始边界
String BOUNDARY = "----------" + System.currentTimeMillis();
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);
String sb = "--" + BOUNDARY + "\r\n" +
"Content-Disposition:form-data;name=\"media\";filename=\"" + filename + "\";filelength=\"" + fileBytes.length + "\"\r\n" +
"Content-Type:application/octet-stream\r\n\r\n";
byte[] head = sb.getBytes(StandardCharsets.UTF_8);
// 创建输出流
OutputStream out = new DataOutputStream(conn.getOutputStream());
out.write(head);
DataInputStream in = new DataInputStream(new ByteArrayInputStream(fileBytes));
int bytes;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
// 设置结束边界
byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes(StandardCharsets.UTF_8);
out.write(foot);
out.flush();
out.close();
StringBuilder buffer = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
// 读取响应
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
} catch (Exception e) {
logger.warn("upload wx material error.", e);
}
//打印结果
System.out.println(JSON.toJSONString(result));