https://blog.csdn.net/tiger3927/article/details/78165980?locationNum=9&fps=1
以下是httpclient的代码
using (var http = new HttpClient())
{
//使用FormUrlEncodedContent做HttpContent
var content = new FormUrlEncodedContent(new Dictionary<string, string>()
{
{"token", steptoken},
{"id", steporderid},
{"driverId", stepdriverid}
});
s_totalwebrequest0++;
var response = await http.PostAsync("http://" + s_webapipro + "/denyOrder", content);
string res = await response.Content.ReadAsStringAsync();
s_totalwebrequest1++;
JObject obj = JObject.Parse(res);
}
以下是httpwebrequest的代码
string url = "http://" + GetWebApiPro() + "/denyOrder";
string postData = "token=" + steptoken + "&id=" + steporderid + "&driverId=" + stepdriverid;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
webRequest.Method = "post";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = byteArray.Length;
System.IO.Stream newStream = webRequest.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
string res = new System.IO.StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();
JObject obj = JObject.Parse(res);
httpwebrequest配合 如下 配置代码,将会提升客户端的并发能力
ServicePointManager.DefaultConnectionLimit = 1024;//提升系统外联的最大并发web访问数
然后在同样的程序环境中使用,都使用如下task异步线程池的方式调用
Task.Run(() =>
{
//上述代码段,其中httpclient需要async修饰符
}
实测效果 httpwebrequest 可以达到4000QPS峰值,2000到3000QPS均值(如果服务器有这么快),相同的访问环境,httpclient只有500平均,800峰值。
结论,httpwebrequest写web客户端或者并发度高的搜索爬虫类软件,效果远好于httpclient。