龙空技术网

C# 模拟Http请求

农码工 1274

前言:

而今小伙伴们对“c语言模拟http”大约比较注意,朋友们都想要了解一些“c语言模拟http”的相关知识。那么小编同时在网上收集了一些关于“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 HttpWebRequestusing 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 = "南轩中学" })));

标签: #c语言模拟http