6

我正在使用 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;
4

1 回答 1

11

问题出在代码的这一部分:

// 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);
于 2012-06-22T17:56:05.340 回答