如何执行在C#中快速Web请求 [英] How to perform a fast web request in C#

查看:232
本文介绍了如何执行在C#中快速Web请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基于HTTP API,我可能需要调用很多次。问题是,我不能请求时间不到20秒,但通过浏览器提出同样的要求是近乎瞬时的。下面的代码演示如何到目前为止执行它

I have a HTTP based API which I potentially need to call many times. The problem is that I can't get the request to take less than about 20 seconds, though the same request made through a browser is near instantaneous. The following code illustrates how I have implemented it so far.

WebRequest r = HttpWebRequest.Create("https://example.com/http/command?param=blabla");
var response = r.GetResponse();



一个解决方案是使异步请求,但我想知道为什么需要这么长,如果我能避免它。我也曾尝试使用WebClient类,但我怀疑它使用一个WebRequest的内部

One solution would be to make an asynchronous request but I would like to know why it takes so long and if I can avoid it. I have also tried using the WebClient class but I suspect it uses a WebRequest internally.

更新:

运行下面的代码花了大约40秒在释放模式(用秒表测量):

Running the following code took about 40 seconds in Release Mode (measured with Stopwatch):

WebRequest g = HttpWebRequest.Create("http://www.google.com");
var response = g.GetResponse();



我在大学里可能有网络配置不同的事情影响工作表现, ,而是直接用浏览器的说明,应该是在瞬间

I'm working at a university where there might be different things in the network configuration affecting the performance, but the direct use of the browser illustrates that it should be near instant.

更新2:

我上传的代码到远程计算机和它的工作细所以得出的结论必须是在.NET代码做一些额外的东西相比,浏览器或具有通过校园网解决地址问题(代理问题或某事?!)。

I uploaded the code to a remote machine and it worked fine so the conclusion must be that the .NET code does something extra compared to the browser or it has problems resolving the address through the university network (proxy issues or something?!).

推荐答案

此问题是类似于在另一个帖子计算器:
#1-2519655(HttpWebRequest的非常慢)

This problem is similar to another post on StackOverflow: Stackoverflow-2519655(HttpWebrequest is extremely slow)

大多数时间的问题是代理服务器属性。您应该将此属性设置为null,否则,对象将尝试寻找合适的代理服务器之前直接到源使用。注:此属性是默认情况下打开,所以你必须明确地告诉该对象不执行此代理搜索

Most of the time the problem is the Proxy server property. You should set this property to null, otherwise the object will attempt to search for an appropriate proxy server to use before going directly to the source. Note: this property is turn on by default, so you have to explicitly tell the object not to perform this proxy search.

request.Proxy = null;
using (var response = (HttpWebResponse)request.GetResponse())
{
}

这篇关于如何执行在C#中快速Web请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆