当使用System.Net.WebClient.DownloadData()方法时,我得到了一个非常慢的响应时间。
在.NET中使用WebClient类获取URL时,需要大约10秒才能获得响应,而使用浏览器获取同一页只需要不到1秒钟。而且这是在数据大小为0.5KB或更小的情况下。
请求涉及POST/GET参数和用户代理标头,如果可能会导致问题。
我还没有尝试过其他在.NET中下载数据的方式是否会给我带来同样的问题,但我怀疑我可能会得到类似的结果。(我一直觉得.NET中的Web请求异常缓慢...)
这可能是什么原因呢?
编辑:
我尝试使用System.Net.HttpWebRequest
代替,使用以下方法进行,所有请求都在1秒钟内完成。
public static string DownloadText(string url)
var request = (HttpWebRequest)WebRequest.Create(url);
var response = (HttpWebResponse)request.GetResponse();
using (var reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
虽然这种使用System.Net.WebClient
的(旧)方法需要15-30秒才能完成每个请求:
public static string DownloadText(string url)
{
var client = new WebClient();
byte[] data = client.DownloadData(url);
return client.Encoding.GetString(data);
}