HttpWebRequest/HttpWebResponse 的速度
有没有比下面的代码更快的替代方法来将 http 响应获取到字符串中?
string req = "http://someaddress.com";
Stopwatch timer = new Stopwatch();
timer.Start();
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream dataStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(dataStream);
reader.ReadToEnd();
}
}
timer.Stop();
Console.WriteLine(timer.Elapsed);
响应相当大 - 大约 2MB,并且采用 XML 格式。此代码完成后,计时器等于约 50 秒。当我将相同的 url 粘贴到浏览器窗口中时,大约需要 35 秒才能显示 xml 文档。
Is there any quicker alternative to the code below to get a http response into a string?
string req = "http://someaddress.com";
Stopwatch timer = new Stopwatch();
timer.Start();
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream dataStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(dataStream);
reader.ReadToEnd();
}
}
timer.Stop();
Console.WriteLine(timer.Elapsed);
The response is pretty big - around 2MB and is in XML format. Affter this codes completes, the timer is equal to ~50 seconds. When I paste the same url into the browser window it takes about 35 seconds for it to display the xml document.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
(顺便说一句,您应该有一个
using
语句作为响应......我同意 asbjornu 的评论。您应该用更多详细信息更新您的问题。)您应该使用类似 Wireshark 查看每种情况下的请求和响应。例如,浏览器是否指定它支持压缩响应,而
WebRequest
不支持?如果连接速度较慢,这很可能是重要的部分。另一件要测试的事情是字符串解码在 .NET 代码中是否花费了大量时间...如果您只是将数据从流读取到字节数组中(可能只是在读取时将其丢弃),那么速度是否明显更快?例如:
(You should have a
using
statement for the response, by the way... and I agree with asbjornu's comment. You should update your question with more details.)You should use something like Wireshark to look at what the requests and responses look like in each case. For example, is the browser specifying that it supports compressed responses, and
WebRequest
not? If it's over a slow connection, that could well be the important part.Another thing to test is whether the string decoding is taking significant time in the .NET code... if you simply read the data from the stream into a byte array (possibly just throwing it away as you read it) is that significantly faster? For example: