使用原因:
在我们服务端调用第三方接口时,如:支付宝,微信支付,我们服务端需要模拟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 HttpWebRequestusing System.IO
方法封装:
/// /// Http请求数据 /// /// 返回类型 /// Url地址 /// Get/Post /// Http参数 /// HttpHeader /// 超时时间(毫秒) /// private T ReqUrlJson(string reqUrl, string method, object paraObject, Dictionary 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
", "")); 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(result); ; } } } /// /// Http请求数据(Post Body form-data 传值形式专用) /// /// 返回类型 /// Url地址 /// HttpHeader /// 超时时间(毫秒) /// private T ReqUrlJson(string reqUrl, Dictionary 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", #34;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(result); }
使用方法:
var response = new MZSABL().ReqUrlJson>("第三方接口地址", "Post", JsonConvert.DeserializeObject>(JsonConvert.SerializeObject(new MZWASerialNumberModel() { school_name = "南轩中学" })));
留言与评论(共有 0 条评论) “” |