HttpWebRequest 到 C# 中的 web 服务;如何从响应流中快速获取数据? [英] HttpWebRequest to web-service in c#; how to get data FAST from the response stream?

查看:41
本文介绍了HttpWebRequest 到 C# 中的 web 服务;如何从响应流中快速获取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 POST 调用 Web 服务并接收 2MB xml.问题是我需要很长时间才能使用流中的数据.响应似乎在 7 秒后出现,但从响应流中读取内容(它是一个字符串)还需要 10 秒.

I am calling a web-service with POST and receiving a 2MB xml. The problem is that it takes to much time until i can use the data within the Stream. The response seems to be after 7 secs there, but it takes another 10 sec to read the content(its a string) from response stream.

Stopwatch s = new Stopwatch();

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(MyUri);
req.Method = "POST";

req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = Poststring.Length;
s.Start();
StreamWriter swriter = new StreamWriter(req.GetRequestStream());
swriter.Write(Poststring);
swriter.Close();

// Get the response. 7 sec
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
s.Stop();
Debug.WriteLine("Talking to Web-Service: "+s.ElapsedMilliseconds);

s.Reset(); 
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);

// Read the content.  10 sec
XmlReader xmlReader = XmlReader.Create(dataStream);
s.Start();
XDocument xdoc = XDocument.Load(xmlReader);
s.Stop(); 
Debug.WriteLine("Convert stream to some useful data: "+s.ElapsedMilliseconds);

以毫秒为单位的输出

Talking to Web-Service: 6595
"Convert" stream to some useful data: 10772

为什么阅读内容需要 10 秒??阅读内容时是否仍然与网络服务进行一些通信或等待数据?它只是一个大约 2MB 的简单文本文件 (xml).我认为那 2 MB 是在 6596 毫秒内传输的.因为当我使用浏览器调用该服务时,xml 内容会在 6-7 秒内显示.

Why does it take like 10 sec to read the content?? Is there stil some communication with the web-service or waiting for data when content is read? Its just a simple textfile (xml) with about 2MB. I thought that those 2 MB were transfered within the 6596 milliseconds. Because when i call that service with my browser, the xml content is shown in 6-7 sec.

与 Web-Service 对话的时间还可以,但是在那 10772 毫秒中发生了什么?

The time for Talking to Web-Service is ok, but what is going on in those 10772 milliseconds?

问题仍然存在.我得到了不同的答案,它们相互矛盾.

The problem is stil there. I get different answers and they contradict each other.

推荐答案

添加以下内容

httpWebRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
httpWebRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

导致:

Talking to Web-Service: 6595
"Convert" stream to some useful data: 256

现在我拥有与浏览器相同的性能!

Now i have the same performance like in a browser!

这篇关于HttpWebRequest 到 C# 中的 web 服务;如何从响应流中快速获取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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