评论

C# 模拟Http请求

原标题:C# 模拟Http请求

使用原因:

在我们服务端调用第三方接口时,如:支付宝,微信支付,我们服务端需要模拟http请求并加上一些自己的逻辑响应给前端最终达到我们想要的效果

1.使用 WebClient

引用命名空间

usingSystem.Net; usingSystem.Collections.Specialized;

Post发送请求

publicvoidTestRequest( ) { using( varclient = newWebClient) { varvalues = newNameValueCollection; values[ "school_name"] = "南轩中学"; values[ "httpWithoutRpc"] = "1"; varresponse = client.UploadValues( "接口地址", values); varresponseString = Encoding.Default.GetString(response); } }

Get发送请求

using( varclient = newWebClient) { varresponseString = client.DownloadString( "接口地址"); }

2.使用WebRequest

我封装两个方法,用于处理post数据传输方式,Post Body form-data 传值形式专用, application/json 这两种常用的,话不多说直接上代码

引用命名空间:

usingHttpWebRequest; usingSystem.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>privateT ReqUrlJson<T>( stringreqUrl, stringmethod, objectparaObject, Dictionary< string, string> headerValue = null, inttimeOut = 50000) {varparamData = JsonConvert.SerializeObject(paraObject);

varrequest = WebRequest.Create(reqUrl) asHttpWebRequest; request.Timeout = timeOut;request.Method = method.ToUpperInvariant; //http method//request.Headers.Add("source", "test"); //headersif(headerValue != null&& headerValue.Count > 0) {foreach( varitem inheaderValue) {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( varresp = request.GetResponse asHttpWebResponse) {using( varstream = newStreamReader(resp.GetResponseStream, Encoding.UTF8)) {stringresult = stream.ReadToEnd; returnJsonConvert.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>privateT ReqUrlJson<T>( stringreqUrl, Dictionary< string, string> headerValue, inttimeOut = 50000) {varclient = newSystem.Net.Http.HttpClient; client.Timeout = TimeSpan.FromMilliseconds(timeOut);varpostContent = newMultipartFormDataContent; stringboundary = 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( varkey inheaderValue.Keys) {postContent.Add( newStringContent(headerValue[key]?.ToString ?? string.Empty), key); }}HttpResponseMessage response = client.PostAsync(reqUrl, postContent).Result;varresult = response.Content.ReadAsStringAsync.Result; returnJsonConvert.DeserializeObject<T>(result); }

使用方法:

varresponse = newMZSABL.ReqUrlJson<MZSAResultModel<MZSASchoolListModel>>( "第三方接口地址", "Post", JsonConvert.DeserializeObject<Dictionary< string, string>>(JsonConvert.SerializeObject( newMZWASerialNumberModel { school_name = "南轩中学"})));

篇尾:

因为本人用的是WebRequest,所以可能WebRequest那写的较详细,封装的两个方法基本上大多数场景都通用哦,如有疑问可以直接私信哦,这里我也推荐大家可以去了解下Post的几种数据传输方式方便更好的理解本篇文章哦~,那本章就到此结束啦

作者:沈威,

版权声明:本文来源于网友收集或网友提供,仅供学习交流之用,如果有侵权,请转告版主或者留言,本公众号立即删除。

支持小薇

腾讯云福利

云服务器入门体验低至6.6元/月,更多浏览

链接:https://curl.qcloud.com/1VVs7OBH

关注: DotNet开发跳槽

觉得不错,请点个在看 返回搜狐,查看更多

责任编辑:

平台声明:该文观点仅代表作者本人,搜狐号系信息发布平台,搜狐仅提供信息存储空间服务。
阅读 ()
大家都在看
推荐阅读