/**
*
* @Title: uploadMedia
* Description:上传头像
* @author houzhipeng
*
* @param type
* @param kf_account
* @param mediaFileUrl void
* @throws
*/
public static void uploadMedia(String type, String kf_account, String mediaFileUrl) {
// 拼装请求地址
String access_token = AccessTokenApi.getAccessToken().getAccessToken();
String uploadMediaUrl = "http://api.weixin.qq.com/customservice/kfaccount/uploadheadimg?access_token="
+ access_token + "&kf_account=" + kf_account;
// 定义数据分隔符
String boundary = "------------7da2e536604c8";
try {
URL uploadUrl = new URL(uploadMediaUrl);
HttpURLConnection uploadConn = (HttpURLConnection) uploadUrl.openConnection();
uploadConn.setDoOutput(true);
uploadConn.setDoInput(true);
uploadConn.setRequestMethod("POST");
// 设置请求头Content-Type
uploadConn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
// 获取媒体文件上传的输出流(往微信服务器写数据)
OutputStream outputStream = uploadConn.getOutputStream();
URL mediaUrl = new URL(mediaFileUrl);
HttpURLConnection meidaConn = (HttpURLConnection) mediaUrl.openConnection();
meidaConn.setDoOutput(true);
meidaConn.setRequestMethod("GET");
// 从请求头中获取内容类型
String contentType = meidaConn.getHeaderField("Content-Type");
// 请求体开始
outputStream.write(("--" + boundary + "\r\n").getBytes());
outputStream.write(String.format("Content-Disposition: form-data; name=\"media\"; filename=\"file1\"\r\n")
.getBytes());
outputStream.write(String.format("Content-Type: %s\r\n\r\n", contentType).getBytes());
// 获取媒体文件的输入流(读取文件)
BufferedInputStream bis = new BufferedInputStream(meidaConn.getInputStream());
byte[] buf = new byte[8096];
int size = 0;
while ((size = bis.read(buf)) != -1) {
// 将媒体文件写到输出流(往微信服务器写数据)
outputStream.write(buf, 0, size);
}
// 请求体结束
outputStream.write(("\r\n--" + boundary + "--\r\n").getBytes());
outputStream.close();
bis.close();
meidaConn.disconnect();
// 获取媒体文件上传的输入流(从微信服务器读数据)
InputStream inputStream = uploadConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer buffer = new StringBuffer();
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
uploadConn.disconnect();
// 使用JSON-lib解析返回结果
JSONObject jsonObject = JSONObject.fromObject(buffer.toString());
// 测试打印结果
System.out.println("打印测试结果" + jsonObject);
} catch (Exception e) {
String error = String.format("上传媒体文件失败:%s", e);
System.out.println(error);
}
}
微信多客服上传头像
最新推荐文章于 2021-03-21 01:34:58 发布