gpt4 book ai didi

c# - 阅读来自 HttpWebResponse 的完整响应

转载 作者:太空宇宙 更新时间:2023-11-03 15:05:17 24 4
gpt4 key购买 nike

我需要从 API 获得完整的响应,但我总是得到 65536 字节内容长度显示 176579。我试着连续阅读,但仍然得到 65536 字节。与 postman 一起,我得到了完整的答案那么从 WebResponse 读取的正确方法是什么?这是我的代码:

string json = Request.ToJson(data);
string method = "POST";
string ContentType = "application/json; charset=utf-8";

HttpWebRequest client = (HttpWebRequest)WebRequest.Create(uri);
client.Method = method;
client.KeepAlive = true;
client.Timeout = 3000;
client.ReadWriteTimeout = 50000;
client.AllowWriteStreamBuffering = true;
client.ContentType = ContentType;

using (var streamWriter = new StreamWriter(client.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}

var errorResponse = client.GetResponse();
byte[] dt = ReadFully(errorResponse.GetResponseStream(), errorResponse.ContentLength);
var str = System.Text.Encoding.Default.GetString(dt);

这是 ReadFully 方法(从另一个答案复制而来):

private byte[] ReadFully(Stream stream, long initialLength)
{
// If we've been passed an unhelpful initial length, just
// use 32K.
byte[] bytes;
using (MemoryStream buffer = new MemoryStream((int)initialLength))
{
byte[] chunk = new byte[initialLength];
int bytesRead;
while ((bytesRead = stream.Read(chunk, 0, chunk.Length)) > 0)
{
buffer.Write(chunk, 0, bytesRead);
}

bytes = buffer.ToArray();
}

return bytes;
}

最佳答案

正如评论中所暗示的那样,errorResponse 变量似乎取自 WebException.Response。读取底层流时有 65536 字节的限制。您可以通过设置以下静态属性来增加此限制:

HttpWebRequest.DefaultMaximumErrorResponseLength = some reasonably large number

关于c# - 阅读来自 HttpWebResponse 的完整响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43842446/

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