java实现上传网络图片到微信服务器
package org.afuos.playcontrol.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class UploadPicToWx {
public String getMediaIdFromUrl(String urlPath, String fileType) throws Exception {
String result = null;
String url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token= Access_token &type=" + fileType + "";
String fileName = urlPath.substring(urlPath.lastIndexOf("/") + 1);
URL mediaUrl = new URL(urlPath);
HttpURLConnection meidaConn = (HttpURLConnection) mediaUrl.openConnection();
meidaConn.setDoOutput(true);
meidaConn.setRequestMethod("GET");
URL urlObj = new URL(url);
HttpURLConnection con = (HttpURLConnection) urlObj.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);
StringBuilder sb = new StringBuilder();
sb.append("--");
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"media\";filename=\"" + fileName + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] head = sb.toString().getBytes("utf-8");
OutputStream out = new DataOutputStream(con.getOutputStream());
out.write(head);
DataInputStream in = new DataInputStream(meidaConn.getInputStream());
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();
meidaConn.disconnect();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
if (result == null) {
result = buffer.toString();
}
} catch (IOException e) {
log.info("发送POST请求出现异常! {}", e);
e.printStackTrace();
throw new IOException("数据读取异常");
} finally {
if (reader != null) {
reader.close();
}
}
JSONObject jsonObj = JSON.parseObject(result);
log.info("getMediaId jsonObj: {}", jsonObj);
return jsonObj.getString("media_id");
}
}
转自:java实现上传网络图片到微信服务器