gpt4 book ai didi

c# - 请求被中止 : The connection was closed unexpectedly

转载 作者:太空狗 更新时间:2023-10-30 00:26:25 26 4
gpt4 key购买 nike

我正在使用此处实现的 Jon Skeet 的 ReadFully 方法:

public static byte[] ReadFully(Stream stream)
{
var buffer = new byte[32768];
using (var ms = new MemoryStream())
{
while (true)
{
int read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0)
return ms.ToArray();
ms.Write(buffer, 0, read);
}
}
}

它在以下行抛出异常:

int read = stream.Read(buffer, 0, buffer.Length);

错误消息是请求被中止:连接意外关闭

我正在向网络服务发送 xml 请求。我的发送方法如下所示:

private static string SendRequest(XElement request, string url)
{
var req = (HttpWebRequest)WebRequest.Create(url);
req.ContentType = "application/soap+xml;";
req.Method = "POST";
req.KeepAlive = false;
req.Timeout = System.Threading.Timeout.Infinite;
req.ReadWriteTimeout = System.Threading.Timeout.Infinite;
req.ProtocolVersion = HttpVersion.Version10;
req.AllowWriteStreamBuffering = false;

using (var stm = req.GetRequestStream())
{
using (var stmw = new StreamWriter(stm))
{
stmw.Write(request.ToString());
}
}

Stream responseStream;
using (var webResponse = req.GetResponse())
{
responseStream = webResponse.GetResponseStream();
}

// Do whatever you need with the response
var myData = ReadFully(responseStream);
string responseString = Encoding.ASCII.GetString(myData);

return responseString;
}

我试过不设置和不设置以下变量,它给了我同样的信息:

req.KeepAlive = false;
req.Timeout = System.Threading.Timeout.Infinite;
req.ReadWriteTimeout = System.Threading.Timeout.Infinite;
req.ProtocolVersion = HttpVersion.Version10;
req.AllowWriteStreamBuffering = false;

最佳答案

问题出在您的这部分代码中:

// wrong way to do it!
Stream responseStream;
using (var webResponse = req.GetResponse())
{
responseStream = webResponse.GetResponseStream();
}

// Do whatever you need with the response
var myData = ReadFully(responseStream);

您在从其流中读取之前处理您的响应对象。尝试这样的事情:

byte[] myData;
using (var webResponse = req.GetResponse())
{
var responseStream = webResponse.GetResponseStream();
myData = ReadFully(responseStream); // done with the stream now, dispose of it
}

// Do whatever you need with the response
string responseString = Encoding.ASCII.GetString(myData);

关于c# - 请求被中止 : The connection was closed unexpectedly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11161516/

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