IT评测·应用市场-qidao123.com
标题:
C# 模拟Http请求
[打印本页]
作者:
瑞星
时间:
2022-9-16 17:15
标题:
C# 模拟Http请求
使用原因:
在我们服务端调用第三方接口时,如:支付宝,微信支付,我们服务端需要模拟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的几种数据传输方式方便更好的理解本片文章哦~,那本章就到此结束啦
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
欢迎光临 IT评测·应用市场-qidao123.com (https://dis.qidao123.com/)
Powered by Discuz! X3.4