C# Post HTTP Request
阿新 • • 發佈:2018-03-05
uil summary padleft reading == start resp 計算 key
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using Network; using Newtonsoft.Json; public static class HttpUtility { /// <summary> /// 創建POST方式的HTTP請求 /// </summary>/// <param name="url"></param> /// <param name="parameters"></param> /// <param name="timeout"></param> /// <param name="userAgent"></param> /// <param name="cookies"></param> /// <returns></returns> public static HttpWebRequest CreatePostHttpResponse(stringurl, IDictionary<string, string> parameters, int timeout, string userAgent, CookieCollection cookies) { HttpWebRequest request = null; //如果是發送HTTPS請求 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { request = WebRequest.Create(url) asHttpWebRequest; } else { request = WebRequest.Create(url) as HttpWebRequest; } request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; //設置代理UserAgent和超時 //request.UserAgent = userAgent; request.Timeout = timeout; if (cookies != null) { request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(cookies); } //發送POST數據 if (!(parameters == null || parameters.Count == 0)) { StringBuilder buffer = new StringBuilder(); int i = 0; foreach (string key in parameters.Keys) { if (i > 0) { buffer.AppendFormat("&{0}={1}", key, parameters[key]); } else { buffer.AppendFormat("{0}={1}", key, parameters[key]); i++; } } byte[] data = Encoding.ASCII.GetBytes(buffer.ToString()); using (var stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } } return request; } /// <summary> /// Post接口 /// </summary> /// <param name="url"></param> /// <param name="parameters"></param> /// <param name="timeout"></param> /// <param name="userAgent"></param> /// <param name="cookies"></param> /// <returns></returns> public static async Task<T> PostHttpRequest(string url,IDictionary<string, string> parameters, int timeout, string userAgent, CookieCollection cookies) { var req = CreatePostHttpResponse(url, parameters, timeout, userAgent, cookies); var res = await req.GetResponseAsync(); if (null == res) { return null; } using (Stream s = res.GetResponseStream()) { StreamReader reader = new StreamReader(s, Encoding.UTF8); var temp = reader.ReadToEnd(); if (string.IsNullOrEmpty(temp)) { return null; } return JsonConvert.DeserializeObject<T>(temp); } } /// <summary> /// MD5計算 /// </summary> /// <param name="appKey"></param> /// <returns></returns> public static string Encrypt_MD5_UTF8(string appKey) { MD5 MD5 = new MD5CryptoServiceProvider(); var datSource = Encoding.GetEncoding("utf-8").GetBytes(appKey); var newSource = MD5.ComputeHash(datSource); var sb = new StringBuilder(32); for (var i = 0; i < newSource.Length; i++) { sb.Append(newSource[i].ToString("x").PadLeft(2, ‘0‘)); } var crypt = sb.ToString(); return crypt; } }
C# Post HTTP Request