WebResponse 接收byte[]不全

冬夜 2016-06-16 10:21:58
求助:
下面的代码 我用注释的代码接收byte[]数据时,数据长度是对的,但是数据只能收到前面的一小部分,其它代码不变用最后两行接收string类型时数据是全的,而且转换成其它对应类时也是正常的,请教下是什么原因引起的?
谢谢!

            WebResponse wr = request.GetResponse();
Stream getStream = wr.GetResponseStream();
//byte[] currentChunk = new byte[wr.ContentLength];
//getStream.Read(currentChunk, 0, currentChunk.Length);

StreamReader sr = new StreamReader(getStream, Encoding.UTF8);
string receiveData = sr.ReadToEnd();


...全文
253 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
冬夜 2016-06-16
  • 打赏
  • 举报
回复
引用 2 楼 Libby1984 的回复:
你这句byte[] currentChunk = new byte[wr.ContentLength];设置数组长度不对。官方解释ContentLength: ContentLength 属性包含与响应一起返回的 Content-Length 标头的值。如果响应中未设置 Content-Length 标头,则将 ContentLength 设置为值 -1。 你应该这么写
byte[] currentChunk = new byte[2048];  // 缓存buffer
int rc=0;  // 每次实际收到的字节数
using(MemoryStream ms = new MemoryStream ())
{
while((rc = getStream.Read(currentChunk, 0, currentChunk.Length)) > 0)
{
          ms.Writ(currentChunk , 0., rc);  // 将当次收到的字节写入流
}

currentChunk  = ms.ToArray();   // 将流转换为byte[]
}
用这个方法解决了,谢谢!
crystal_lz 2016-06-16
  • 打赏
  • 举报
回复

int index = 0;
while(index < currentChunk.Length){
    index += getStream.Read(currentChunk,index,currentChunk.Length - index);
}
我猜的。。。。。。
xdashewan 2016-06-16
  • 打赏
  • 举报
回复
不是二进制数据直接ReadToEnd,最多再字符串转byte数组,两句代码的事
  • 打赏
  • 举报
回复
你这句byte[] currentChunk = new byte[wr.ContentLength];设置数组长度不对。官方解释ContentLength: ContentLength 属性包含与响应一起返回的 Content-Length 标头的值。如果响应中未设置 Content-Length 标头,则将 ContentLength 设置为值 -1。 你应该这么写
byte[] currentChunk = new byte[2048];  // 缓存buffer
int rc=0;  // 每次实际收到的字节数
using(MemoryStream ms = new MemoryStream ())
{
while((rc = getStream.Read(currentChunk, 0, currentChunk.Length)) > 0)
{
          ms.Writ(currentChunk , 0., rc);  // 将当次收到的字节写入流
}

currentChunk  = ms.ToArray();   // 将流转换为byte[]
}
Forty2 2016-06-16
  • 打赏
  • 举报
回复
int 实收长度 = 0; 实收长度 += getStream.Read(currentChunk, 0, currentChunk.Length); if (实收长度 < currentChunk.Length) { 实收长度 += getStream.Read(currentChunk, 实收长度 , currentChunk.Length - 实收长度 ); }

110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧