C# UWP HttpWebResponse Chunked

本文关键字:Chunked HttpWebResponse UWP | 更新日期: 2023-09-27 18:22:26

我在读取流响应时遇到问题,因为我无法读取到结束的响应。

这是来自服务器的响应:

 Server : "Apache-Coyote/1.1"
 Transfer-Encoding : "chunked"
 Content-Type: "multipart/mixed; boundary=F34D3847AEDEB14FF5967BF7426EECF6"

我试着阅读这个回复:

var response = (HttpWebResponse)await httpWebRequest.GetResponseAsync();
using(var read = new StreamReader(response.GetResponseStream())
 {
   var result = await read.ReadToEndAsync();
 }

这种方法:

StringBuilder sb = new StringBuilder();
Byte[] buf = new byte[8192];
Stream resStream = response.GetResponseStream();
string tmpString = null;
int count = 0;
do
{
count = resStream.Read(buf, 0, buf.Length);
if(count != 0)
{
      tmpString = Encoding.ASCII.GetString(buf, 0, count);
      sb.Append(tmpString);
}
}while (count > 0);

错误消息:

Exception from HRESULT: 0x80072EE4
I/O error occurred.
Exception thrown: 'System.IO.IOException' in mscorlib.ni.dll
Exception thrown: 'System.IO.IOException' in mscorlib.ni.dll

不幸的是,它不起作用,只得到部分响应。感谢您的帮助

C# UWP HttpWebResponse Chunked

我测试了你的代码,对于你采用的第一个方法,我觉得它很好,我只是在其中添加了一个Dispose()。对于第二个方法,可能是你没有得到var responseContentLength的问题。

这是我的代码,代码中注释的部分是第一个方法,我使用了一个Button Click事件来处理:

  public async void HTTP(object sender, RoutedEventArgs e)
        {
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("URL");
            HttpWebResponse response = (HttpWebResponse)await httpWebRequest.GetResponseAsync();
            Stream resStream = response.GetResponseStream();            
            StringBuilder sb = new StringBuilder();
            StreamReader read = new StreamReader(resStream);
            string tmpString = null;
            int count = (int)response.ContentLength;
            int offset = 0;
            Byte[] buf = new byte[count];
            do
            {
                int n = resStream.Read(buf, offset, count);
                if (n == 0) break;
                count -= n;
                offset += n;
                tmpString = Encoding.ASCII.GetString(buf, 0, buf.Length);
                sb.Append(tmpString);
            } while (count > 0);
            text.Text = tmpString;

            read.Dispose();
            //using (StreamReader read = new StreamReader(resStream))
            //{
            //    var result = await read.ReadToEndAsync();
            //    text.Text = result;
            //    read.Dispose();
            //}
            response.Dispose();
        }

我测试过了,效果很好。