使用原因: 在我們服務端調用第三方介面時,如:支付寶,微信支付,我們服務端需要模擬http請求並加上一些自己的邏輯響應給前端最終達到我們想要的效果 1.使用WebClient 引用命名空間 using System.Net; using System.Collections.Specialized; ...
使用原因:
在我們服務端調用第三方介面時,如:支付寶,微信支付,我們服務端需要模擬http請求並加上一些自己的邏輯響應給前端最終達到我們想要的效果
1.使用WebClient
引用命名空間
using System.Net; using System.Collections.Specialized;
Post發送請求
public void TestRequest() { using (var client = new WebClient()) { var values = new NameValueCollection(); values["school_name"] = "南軒中學"; values["httpWithoutRpc"] = "1"; var response = client.UploadValues("介面地址", values); var responseString = Encoding.Default.GetString(response); } }
Get發送請求
using (var client = new WebClient()) { var responseString = client.DownloadString("介面地址"); }
2.使用WebRequest
我封裝兩個方法,用於處理post數據傳輸方式,Post Body form-data 傳值形式專用, application/json 這兩種常用的,話不多說直接上代碼
引用命名空間:
using HttpWebRequest using System.IO
方法封裝:
/// <summary> /// Http請求數據 /// </summary> /// <typeparam name="T">返回類型</typeparam> /// <param name="reqUrl">Url地址</param> /// <param name="method">Get/Post</param> /// <param name="paraObject">Http參數</param> /// <param name="headerValue">HttpHeader</param> /// <param name="timeOut">超時時間(毫秒)</param> /// <returns></returns> private T ReqUrlJson<T>(string reqUrl, string method, object paraObject, Dictionary<string, string> headerValue = null, int timeOut = 50000) { var paramData = JsonConvert.SerializeObject(paraObject); var request = WebRequest.Create(reqUrl) as HttpWebRequest; request.Timeout = timeOut; request.Method = method.ToUpperInvariant(); //http method //request.Headers.Add("source", "test"); //headers if (headerValue != null && headerValue.Count > 0) { foreach (var item in headerValue) { if (!string.IsNullOrEmpty(item.Key) && !string.IsNullOrEmpty(item.Value)) { request.Headers.Add(item.Key, item.Value); } } } //處理post請求 if (request.Method != "GET" && !string.IsNullOrEmpty(paramData) && paramData.Length > 0) //request data { request.ContentType = "application/json"; byte[] buffer = Encoding.UTF8.GetBytes(paramData.Replace("\r\n", "")); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); } using (var resp = request.GetResponse() as HttpWebResponse) { using (var stream = new StreamReader(resp.GetResponseStream(), Encoding.UTF8)) { string result = stream.ReadToEnd(); return JsonConvert.DeserializeObject<T>(result); ; } } } /// <summary> /// Http請求數據(Post Body form-data 傳值形式專用) /// </summary> /// <typeparam name="T">返回類型</typeparam> /// <param name="reqUrl">Url地址</param> /// <param name="headerValue">HttpHeader</param> /// <param name="timeOut">超時時間(毫秒)</param> /// <returns></returns> private T ReqUrlJson<T>(string reqUrl, Dictionary<string, string> headerValue, int timeOut = 50000) { var client = new System.Net.Http.HttpClient(); client.Timeout = TimeSpan.FromMilliseconds(timeOut); var postContent = new MultipartFormDataContent(); string boundary = string.Format("--{0}", DateTime.Now.Ticks.ToString("x")); postContent.Headers.Add("ContentType", $"multipart/form-data, boundary={boundary}"); //postContent.Headers.Add("source", "test"); if (headerValue != null && headerValue.Count > 0) { foreach (var key in headerValue.Keys) { postContent.Add(new StringContent(headerValue[key]?.ToString() ?? string.Empty), key); } } HttpResponseMessage response = client.PostAsync(reqUrl, postContent).Result; var result = response.Content.ReadAsStringAsync().Result; return JsonConvert.DeserializeObject<T>(result); }
使用方法:
var response = new MZSABL().ReqUrlJson<MZSAResultModel<MZSASchoolListModel>>("第三方介面地址", "Post", JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonConvert.SerializeObject(new MZWASerialNumberModel() { school_name = "南軒中學" })));
篇尾:
因為本人用的是WebRequest,所以可能WebRequest那寫的較詳細,封裝的兩個方法基本上大多數場景都通用哦,如有疑問可以直接私信哦,這裡我也推薦大家可以去瞭解下Post的幾種數據傳輸方式方便更好的理解本片文章哦~,那本章就到此結束啦
本文來自博客園,作者:沈威,轉載請註明原文鏈接:https://www.cnblogs.com/shenweif/p/16564975.html