java微信上传永久素材

网上找了一大圈关于java微信上传永久素材的问题,少得很。我把我弄得代码共享一下,额,也是网上找来整合的。勿喷.



public static JSONObject uploadPermanentMediaFile(String requestUrl, File file, String type) {


StringBuffer buffer = new StringBuffer();
JSONObject jsonObject = null;
try {


String boundary = "*****"; // 用于拼接 可自定义
URL url = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(20000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
// 请求正文信息
// 第一部分:
StringBuilder sb = new StringBuilder();
sb.append("--"); // 必须多两道线
sb.append(boundary);
sb.append("\r\n");
/***********************************/
sb.append("Content-Disposition: form-data;name=\"type\" \r\n\r\n");
sb.append(type);
sb.append("\r\n--").append(boundary).append("\r\n");
if ("video".equals(type)) {
sb.append("Content-Disposition: form-data;name=\"description\" \r\n\r\n");
sb.append("{\"title\":\"hello title\",\"introduction\":\"hello introduction\"}");
sb.append("\r\n--").append(boundary).append("\r\n");
}
/***********************************/
String filename = file.getName();
sb.append("Content-Disposition: form-data;name=\"media\";filename=\"" + filename + "\" \r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
System.out.println(sb.toString());
byte[] head = sb.toString().getBytes("utf-8");
// 获得输出流
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
// 输出表头
out.write(head);
// 文件正文部分
// 把文件已流文件的方式 推入到url中
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
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("utf-8");// 定义最后数据分隔线
out.write(foot);
out.flush();
out.close();


// 定义BufferedReader输入流来读取URL的响应
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
jsonObject = JSONObject.fromObject(buffer.toString());
} catch (Exception e) {
e.printStackTrace();
}
return jsonObject;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值