C# 實現http get post async sync 上傳檔案
阿新 • • 發佈:2018-11-09
程式碼:
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { public static class HttpRequestHelper { public delegate int handleAsync(string str); /// <summary> /// Http Get Request /// </summary> /// <param name="url"></param> /// <returns></returns> public static string HttpGetRequest(string url) { string strGetResponse = string.Empty; try { var getRequest = CreateHttpRequest(url, "GET"); var getResponse = getRequest.GetResponse() as HttpWebResponse; strGetResponse = GetHttpResponse(getResponse, "GET"); } catch (Exception ex) { strGetResponse = ex.Message; } return strGetResponse; } /// <summary> /// Http Get Request Async /// </summary> /// <param name="url"></param> public static async void HttpGetRequestAsync(string url) { string strGetResponse = string.Empty; try { var getRequest = CreateHttpRequest(url, "GET"); var getResponse = await getRequest.GetResponseAsync() as HttpWebResponse; strGetResponse = GetHttpResponse(getResponse, "GET"); } catch (Exception ex) { strGetResponse = ex.Message; } Console.WriteLine("reslut:" + strGetResponse); //return strGetResponse; } /// <summary> /// Http Post Request /// </summary> /// <param name="url"></param> /// <param name="postJsonData"></param> /// <returns></returns> public static string HttpPostRequest(string url, string postJsonData) { string strPostReponse = string.Empty; try { var postRequest = CreateHttpRequest(url, "POST", postJsonData); var postResponse = postRequest.GetResponse() as HttpWebResponse; strPostReponse = GetHttpResponse(postResponse, "POST"); } catch (Exception ex) { strPostReponse = ex.Message; } return strPostReponse; } /// <summary> /// Http Post Request Async /// </summary> /// <param name="url"></param> /// <param name="postJsonData"></param> public static async void HttpPostRequestAsync(string url, string postData, handleAsync ha=null) { string strPostReponse = string.Empty; try { var postRequest = CreateHttpRequest(url, "POST", postData); var postResponse = await postRequest.GetResponseAsync() as HttpWebResponse; strPostReponse = GetHttpResponse(postResponse, "POST"); } catch (Exception ex) { strPostReponse = ex.Message; } if (strPostReponse != "true") { //Console.WriteLine("--> reslut : " + strPostReponse); //Console.WriteLine(postData); if(null != ha) { ha(strPostReponse); } } } public static string HttpUploadFile(string url, int timeOut, string fileKeyName, string filePath, Dictionary<string, string> list) { string responseContent; var memStream = new MemoryStream(); var webRequest = (HttpWebRequest)WebRequest.Create(url); // 邊界符 var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");//日期的16進位制字串 // 邊界符 var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n"); // 最後的結束符 var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n"); // 設定屬性 webRequest.Method = "POST"; webRequest.Timeout = timeOut; webRequest.ContentType = "multipart/form-data; boundary=" + boundary; // 寫入檔案----------1.-------------- // 獲取檔名稱路徑最後一級,以\/分級,不分級則取全路徑為檔名 int start = filePath.LastIndexOf("/"); if(-1 == start) { start = filePath.LastIndexOf("\\"); if(-1 == start) { start = 0; } } string filename = filePath.Substring(start + 1); string filePartHeader = "Content-Disposition: form-data; name=\"{0}\"; filename=" + filename + "\r\n" + "Content-Type: application/octet-stream\r\n\r\n"; var header = string.Format(filePartHeader, fileKeyName, filePath); Console.WriteLine(header); var headerbytes = Encoding.UTF8.GetBytes(header); memStream.Write(beginBoundary, 0, beginBoundary.Length); memStream.Write(headerbytes, 0, headerbytes.Length); // 獲取檔案流 var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read); var buffer = new byte[1024]; int bytesRead; // =0 // 檔案流寫入緩衝區 while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { memStream.Write(buffer, 0, bytesRead); } // 檔案後面要有換行 string stringKeyHeader = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n"; // 遍歷引數,傳輸資料的編碼集----------- 2 ------------------- foreach (var item in list) { // var dataByte = Encoding.UTF8.GetBytes(string.Format(stringKeyHeader, item.Key, item.Value)); memStream.Write(dataByte, 0, dataByte.Length); } // 寫入最後的結束邊界符------------ 3.------------------------- memStream.Write(endBoundary, 0, endBoundary.Length); webRequest.ContentLength = memStream.Length; var requestStream = webRequest.GetRequestStream(); memStream.Position = 0; var tempBuffer = new byte[memStream.Length]; memStream.Read(tempBuffer, 0, tempBuffer.Length); memStream.Close(); requestStream.Write(tempBuffer, 0, tempBuffer.Length); requestStream.Close(); // 響應 ------------------- 4.----------------------------------- var httpWebResponse = (HttpWebResponse)webRequest.GetResponse(); using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding("utf-8"))) { responseContent = httpStreamReader.ReadToEnd(); } fileStream.Close(); httpWebResponse.Close(); webRequest.Abort(); return responseContent; } private static HttpWebRequest CreateHttpRequest(string url, string requestType, string strJson="") { HttpWebRequest request = null; const string get = "GET"; const string post = "POST"; if (string.Equals(requestType, get, StringComparison.OrdinalIgnoreCase)) { request = CreateGetHttpWebRequest(url); } if (string.Equals(requestType, post, StringComparison.OrdinalIgnoreCase)) { request = CreatePostHttpWebRequest(url, strJson); } return request; } private static HttpWebRequest CreateGetHttpWebRequest(string url) { var getRequest = HttpWebRequest.Create(url) as HttpWebRequest; getRequest.Method = "GET"; getRequest.Timeout = 5000; getRequest.ContentType = "text/html;charset=UTF-8"; getRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; return getRequest; } private static HttpWebRequest CreatePostHttpWebRequest(string url, string postData) { var postRequest = HttpWebRequest.Create(url) as HttpWebRequest; postRequest.KeepAlive = false; postRequest.Timeout = 5000; postRequest.Method = "POST"; postRequest.ContentType = "application/x-www-form-urlencoded"; postRequest.ContentLength = postData.Length; postRequest.AllowWriteStreamBuffering = false; StreamWriter writer = new StreamWriter(postRequest.GetRequestStream(), Encoding.ASCII); writer.Write(postData); writer.Flush(); return postRequest; } private static string GetHttpResponse(HttpWebResponse response, string requestType) { var responseResult = ""; const string post = "POST"; string encoding = "UTF-8"; if (string.Equals(requestType, post, StringComparison.OrdinalIgnoreCase)) { encoding = response.ContentEncoding; if (encoding == null || encoding.Length < 1) { encoding = "UTF-8"; } } using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding))) { responseResult = reader.ReadToEnd(); } return responseResult; } private static string GetHttpResponseAsync(HttpWebResponse response, string requestType) { var responseResult = ""; const string post = "POST"; string encoding = "UTF-8"; if (string.Equals(requestType, post, StringComparison.OrdinalIgnoreCase)) { encoding = response.ContentEncoding; if (encoding == null || encoding.Length < 1) { encoding = "UTF-8"; } } using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding))) { responseResult = reader.ReadToEnd(); } return responseResult; } //dictionary轉http get引數 public static string DictoryToGetParam(Dictionary<string, string> dict) { string param = ""; foreach(KeyValuePair<string, string> kv in dict) { param += kv.Key + '=' + kv.Value + '&'; } if('&' == param[param.Length - 1]) { param = param.Substring(0, param.Length - 1); } return param; } } }
同步呼叫
//同步http post static void testHttp() { var postUrl = "http://yoururl"; Dictionary<string, string> postData = new Dictionary<string, string>(); postData.Add("userID", "100000048"); postData.Add("gradeID", "1"); // 自己實現的http請求 string postStr = HttpRequestHelper.DictoryToGetParam(postData); var repose = HttpRequestHelper.HttpPostRequest(postUrl, postStr); Console.WriteLine(repose); }
非同步呼叫
static void testHttpAsync() { var postUrl = "http://yoururl"; Dictionary<string, string> postData = new Dictionary<string, string>(); postData.Add("userID", "100000048"); postData.Add("gradeID", "1"); string postStr = HttpRequestHelper.DictoryToGetParam(postData); //類中static回撥函式handlePostAsync HttpRequestHelper.HttpPostRequestAsync(getUrl, postStr, handlePostAsync); Console.WriteLine("http post async done"); Console.Read(); } //回撥函式 static int handlePostAsync(string str) { Console.WriteLine("handle post Async : " + str); return 0; }
單檔案上傳帶引數
static void testFileUpload()
{
var postUrl = "http://yoururl";
Dictionary<string, string> postData = new Dictionary<string, string>();
postData.Add("userID", "100000048");
postData.Add("gradeID", "1");
string returnData = HttpRequestHelper.HttpUploadFile(postUrl, 12000, "qrcode_image", "D://0//huojian.png", postData);
Console.WriteLine(returnData);
Console.Read();
}