/**
* 上传多媒体文件到微信公众平台
* @param fileType 文件类型
* @param access_token //在微信平台获取到的凭证
* @param filename 文件名称
* @param file 文件流
* @param content_type 文件类型
* @param filePath 文件路径
* @return
*/
public static JSON uploadmedia(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="http://file.api.weixin.qq.com/cgi-bin/media/upload?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=\""+file.length() / 1024 +";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 = JSONObject.fromObject(result); //获取到返回Json请自行根据返回码获取相应的结果
return json;
}
public static void main(String[] args) throws IOException {
JSON json = uploadmedia("image", "MKRGxuzca1jZn6s2vJ5IPXhj88cOy8aheJ-5r75HL4hLnLXs_o960GnfGMh9KJooTxwwr0qPlRwALSyrFlpJ-w", "jiqimao", new File("D:\\jiqimao.jpg"), "image/jpeg", "D:\\jiqimao.jpg");
System.out.println(json.toString());
}
java模拟上传多媒体文件到微信公众平台
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.