asp.net 模擬CURL調用微信公共平臺API 上傳下載多媒體文

近公司項目上在開發微信服務號的接口,須要給用戶回覆圖片或語音或視頻,這個時候就須要用到 上傳下載多媒體文件接口,微信在這方面推薦採用的是開源函數庫curl實現的,CURL項目包括不少版本,我主要測試的是windows 平臺下的版本,是很好用的,下面附上說明及CURL下載地址
在asp.net中,能夠調用cmd命令行,運行這個腳本,實現上傳下載的功能,但我須要講的重點不在此,作爲一個在線運行的項目,容許網站目錄下能夠運行.exe的程序是很是不安全的,因此接下來的DEMO是採用asp.net(c#)的方式,調用微信的這個API接口

很少說,上代碼

總共有二個類,一個枚舉

FormItem類



public class FormItem

{

public string Name { get; set; }

public ParamType ParamType { get; set; }

public string Value { get; set; }

}

ParamType枚舉

public enum ParamType



///

/// 文本類型

///

Text,

///

/// 文件路徑,須要全路徑(例:C:\A.JPG)

///

File

}

Funcs靜態類

public static class Funcs

{

public static string PostFormData(List list,string uri)

{

string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");

//請求 

WebRequest req = WebRequest.Create(uri);

req.Method = "POST";

req.ContentType = "multipart/form-data; boundary=" + boundary;

//組織表單數據 

StringBuilder sb = new StringBuilder();

foreach (FormItem item in list)

{

switch (item.ParamType)

{

case ParamType.Text:

sb.Append("--" + boundary);

sb.Append("\r\n");

sb.Append("Content-Disposition: form-data; name="" + item.Name + """);

sb.Append("\r\n\r\n");

sb.Append(item.Value);

sb.Append("\r\n");

break;

case ParamType.File:

sb.Append("--" + boundary);

sb.Append("\r\n");

sb.Append("Content-Disposition: form-data; name="media"; filename=""+item.Value+""");

sb.Append("\r\n");

sb.Append("Content-Type: application/octet-stream");

sb.Append("\r\n\r\n");

break;

}

}

string head = sb.ToString();

//post字節總長度

long length = 0;

byte[] form_data = Encoding.UTF8.GetBytes(head);

//結尾 

byte[] foot_data = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

List fileList = list.Where(f => f.ParamType == ParamType.File).ToList();

length = form_data.Length + foot_data.Length;

foreach (FormItem fi in fileList)

{

FileStream fileStream = new FileStream(fi.Value, FileMode.Open, FileAccess.Read);

length += fileStream.Length;

fileStream.Close();

}

req.ContentLength = length; 


Stream requestStream = req.GetRequestStream();

//發送表單參數 

requestStream.Write(form_data, 0, form_data.Length);

foreach (FormItem fd in fileList)

{

FileStream fileStream = new FileStream(fd.Value, FileMode.Open, FileAccess.Read);

//文件內容 

byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];

int bytesRead = 0;

while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)

requestStream.Write(buffer, 0, bytesRead);

//結尾 

requestStream.Write(foot_data, 0, foot_data.Length);

}

requestStream.Close();


//響應 

WebResponse pos = req.GetResponse();

StreamReader sr = new StreamReader(pos.GetResponseStream(), Encoding.UTF8);

string html = sr.ReadToEnd().Trim();

sr.Close();

if (pos != null)

{

pos.Close();

pos = null;

}

if (req != null)

{

req = null;

}

return html;

}

///

/// 從URL地址下載文件到本地磁盤

///

/// 本地磁盤地址

/// URL網址

///

public static string SaveFileFromUrl(string FileName, string Url)

{

WebResponse response = null;

Stream stream = null;

try

{

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);

response = request.GetResponse();

stream = response.GetResponseStream();


if (!response.ContentType.ToLower().StartsWith("text/"))

{

SaveBinaryFile(response, FileName);

}

else

{

StreamReader sr = new StreamReader(stream, System.Text.Encoding.UTF8);

return sr.ReadToEnd();

}


}

catch (Exception err)

{

return err.ToString();

}

return "complete";

}

///

/// 將二進制文件保存到磁盤

///

/// 將二進制文件保存到磁盤

// 將二進制文件保存到磁盤

private static bool SaveBinaryFile(WebResponse response, string FileName)

{

bool Value = true;

byte[] buffer = new byte[1024];


try

{

if (File.Exists(FileName))

File.Delete(FileName);

Stream outStream = System.IO.File.Create(FileName);

Stream inStream = response.GetResponseStream();


int l;

do

{

l = inStream.Read(buffer, 0, buffer.Length);

if (l > 0)

outStream.Write(buffer, 0, l);

}

while (l > 0);


outStream.Close();

inStream.Close();

}

catch

{

Value = false;

}

return Value;

}

}

調用代碼


//新建一個form表單項,就是須要提交哪些字段和數據的列表

List list = new List();

//添加微信接口上的access_token參數,注意,access_token是有過時時間的,代碼中的access_token確定過時了,獲取access_token的地址請點擊我,須要有本身的服務號纔會有的

list.Add(new FormItem() { Name = "access_token", ParamType =
ParamType.Text, Value = "MlfTORyg_dRTuiQThmKUxVVkK7q_SMEd0y9GwBmj6NJw3E0J
2jVnC3RxgdO1Yjog2QD4DDxhdqEkZaklR7czq8sSbW4mnhM7n9-5lIIymVGkrBAv2nnnk
tUyYcuYTMs2SYtp-pn6IWEtTpsFVlUFZQ" });

//添加FORM表單中這條數據的類型,目前只作了兩種,一種是文本,一種是文件

list.Add(new FormItem() { Name = "type", Value = "image", ParamType = ParamType.Text });

//添加Form表單中文件的路徑,路徑必須是基於硬盤的絕對路徑

list.Add(new FormItem() { Name = "media", Value = @"d:\1.jpg", ParamType = ParamType.File });

//經過Funcs靜態類中的PostFormData方法,將表單數據發送至http://file.api.weixin.qq.com/cgi-bin/media/upload騰訊上傳下載文件接口


string result = Funcs.PostFormData(list, "http://file.api.weixin.qq.com/cgi-bin/media/upload");

//獲取返回值,並取出的結果中的media_id,注意,有可能返回的是騰訊的錯誤代碼,請自行判斷

System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();

var mydata=jss.Deserialize(result);

//經過Funcs靜態類中的SaveFileFromUrl方法,將指定微信media_id的文件下載到本機

var saveResult=Funcs.SaveFileFromUrl(@"d:\lee.jpg", "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=MlfTORyg_dRTuiQThmKUxVVkK7q_SMEd0y9GwBmj6NJw3E0J2jVnC3RxgdO1Yjog2QD4DDxhdqEkZaklR7czq8sSbW4mnhM7n9-5lIIymVGkrBAv2nnnktUyYcuYTMs2SYtp-pn6IWEtTpsFVlUFZQ&media_id=" + mydata["media_id"].ToString());
  


這樣就完成了模擬CURL調用微信上傳下載多媒體文件的接口


不知道你們有沒有其它更好或更方便的辦法,歡迎與我討論

若是有須要的朋友,調用過程當中有問題,歡迎私信給我,我能夠把DEMO發給他html

相關文章
相關標籤/搜索