http编程实例(C模拟Http请求)

使用原因:

在我们服务端调用第三方接口时,如:支付宝,微信支付,我们服务端需要模拟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 = "南轩中学" })));

,

免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com

    分享
    投诉
    首页