tft每日頭條

 > 生活

 > http編程實例

http編程實例

生活 更新时间:2024-08-07 08:13:58

使用原因:

在我們服務端調用第三方接口時,如:支付寶,微信支付,我們服務端需要模拟http請求并加上一些自己的邏輯響應給前端最終達到我們想要的效果

1.使用WebClient

引用命名空間

using System.Net; using System.Collections.Specialized;

Post發送請求

http編程實例(C模拟Http請求)1

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); } }

http編程實例(C模拟Http請求)2

Get發送請求

using (var client = new WebClient()) { var responseString = client.DownloadString("接口地址"); }

2.使用WebRequest

我封裝兩個方法,用于處理post數據傳輸方式,Post Body form-data 傳值形式專用, application/json 這兩種常用的,話不多說直接上代碼

引用命名空間:

using HttpWebRequest using System.IO

方法封裝:

http編程實例(C模拟Http請求)3

/// <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); }

http編程實例(C模拟Http請求)4

使用方法:

var response = new MZSABL().ReqUrlJson<MZSAResultModel<MZSASchoolListModel>>("第三方接口地址", "Post", JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonConvert.SerializeObject(new MZWASerialNumberModel() { school_name = "南軒中學" })));

,

更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!

查看全部

相关生活资讯推荐

热门生活资讯推荐

网友关注

Copyright 2023-2024 - www.tftnews.com All Rights Reserved