/**
* 上傳多媒體文件到微信公衆平臺
* @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模擬上傳多媒體文件到微信公衆平臺
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.