public static WeixinMedia uploadMedia(String accessToken, String type, String mediaFileUrl) {
WeixinMedia weixinMedia = null;
// 拼裝請求地址
String uploadMediaUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
uploadMediaUrl = uploadMediaUrl.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type);
// 定義數據分隔符
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");
// 根據內容類型判斷文件擴展名
String fileExt = WeixinUtil.getFileEndWitsh(contentType);
// 請求體開始
outputStream.write(("--" + boundary + "\r\n").getBytes());
outputStream.write(String.format("Content-Disposition: form-data; name=\"media\"; filename=\"file1%s\"\r\n", fileExt).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);
weixinMedia = new WeixinMedia();
weixinMedia.setType(jsonObject.getString("type"));
// type等於 縮略圖(thumb) 時的返回結果和其它類型不一樣
if ("thumb".equals(type))
weixinMedia.setMediaId(jsonObject.getString("thumb_media_id"));
else
weixinMedia.setMediaId(jsonObject.getString("media_id"));
weixinMedia.setCreatedAt(jsonObject.getInt("created_at"));
} catch (Exception e) {
weixinMedia = null;
String error = String.format("上傳媒體文件失敗:%s", e);
System.out.println(error);
}
return weixinMedia;
}
轉換成c#代碼
看看HttpWebRequest/HttpWebResponse