gpt4 book ai didi

c# - WebRequest GetResponseStream 读取字节

转载 作者:太空狗 更新时间:2023-10-29 21:35:45 25 4
gpt4 key购买 nike

我正在尝试从 ResponeStream 读取字节,但我怎么能说要等待数据呢?

如果我在 GetResponseStream 之后设置断点并等待几秒钟,一切正常。使用 StreamReader.ReadToEnd() 也可以正常工作,但我想自己读取字节。

byte[] response = null;

int left = 0;
int steps = 0;
int pos = 0;

int bytelength = 1024;

OnReceiveStart();

using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse()) {
using (Stream sr = webResponse.GetResponseStream()) {

response = new byte[(int)webResponse.ContentLength];

left = (int)webResponse.ContentLength % bytelength;
steps = (int)webResponse.ContentLength / bytelength;
pos = 0;

for (int i = 0; i < steps; i++) {
sr.Read(response, pos, bytelength);
pos += bytelength;
OnReceiveProgress((int)webResponse.ContentLength, pos);
}

if (left != 0) {
sr.Read(response, pos, left);
}

sr.Close();
}
webResponse.Close();
}

OnReceiveProgress(1, 1);

OnReceiveFinished();

最佳答案

只是不要将其分解为相同数量的步骤 - 相反,只需继续循环阅读直到完成:

while (pos < response.Length)
{
int bytesRead = sr.Read(response, pos, response.Length - pos);
if (bytesRead == 0)
{
// End of data and we didn't finish reading. Oops.
throw new IOException("Premature end of data");
}
pos += bytesRead;
OnReceiveProgress(response.Length, pos);
}

请注意,您必须使用 Stream.Read 的返回值 - 您不能假设它会读取您请求的所有内容为。

关于c# - WebRequest GetResponseStream 读取字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8490605/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com