标签:
/**
* 上传多媒体文件到微信公众平台
*
* @author w_a
*
* 2014-11-27
*
* @param fileType
* 文件类型
* @param access_token
* //在微信平台获取到的凭证
* @param filename
* 文件名称
* @param file
* 文件流
* @param content_type
* 文件类型
* @param filePath
* 文件路径
* @return
*/
public static JSON UploadMedia(String httpUrl, String fileType, String access_token, String filename, File file, String content_type, String filePath) {
String result = "";
String end = "\r\n";
String twoHyphens = "--"; // 用于拼接
String boundary = "*****"; // 用于拼接 可自定义
URL submit = null;
JSONObject json = null;
String requestUrl = httpUrl + "?access_token=" + access_token + "&type=" + fileType;
try {
submit = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) submit.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
// 获取输出流对象,准备上传文件
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + end);
dos.writeBytes("Content-Disposition: form-data; name=\"" + file + "\";filename=\"" + filename + ";filelength=\"" + filePath + ";Content-Type=\"" + content_type + end);
dos.writeBytes(end);
// 对文件进行传输
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[8192]; // 8k
int count = 0;
while ((count = fis.read(buffer)) != -1) {
dos.write(buffer, 0, count);
}
// 关闭文件流
fis.close();
dos.writeBytes(end);
dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
dos.flush();
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
result = br.readLine();
dos.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("与服务器连接发生异常错误:" + e.toString());
System.out.println("连接地址是:" + requestUrl);
}
// 获取到返回Json请自行根据返回码获取相应的结果
json = JSONObject.parseObject(result);
return json;
}
标签:
原文地址:http://www.cnblogs.com/xunfang123/p/4196152.html