我正在使用 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);
错误消息是The request was aborted: The connection was closed unexpectedly
。
我正在向 Web 服务发送 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;