WebRequest GetResponse没有响应,操作超时

本文关键字:操作 超时 响应 GetResponse WebRequest | 更新日期: 2023-09-27 18:05:14

我正试图使HttpWebRequest通过POST向REST web服务发送数据,然后在处理后使用额外的HttpWebRequest下载响应。

POST向web服务发送二进制数据,如下所示:

HttpWebRequest uploadRequest = (HttpWebRequest)WebRequest.Create(baseAddress + uploadURIRequest);
uploadRequest.Timeout = Timeout.Infinite;
uploadRequest.ReadWriteTimeout = Timeout.Infinite;
uploadRequest.Method = "POST";
uploadRequest.ContentLength = fileInfo.Length;
uploadRequest.ContentType = "application/octet-stream";
using (Stream writeStream = uploadRequest.GetRequestStream())
{
    using (FileStream readStream = new FileStream(fileStreamFileName, FileMode.Open, FileAccess.Read))
    {
        byte[] data= new byte[readStream.Length];
        int bytesRead = readStream.Read(data, 0, (int)readStream.Length);
        writeStream.Write(data, 0, bytesRead);
        readStream.Close();
    }
    writeStream.Close();
}

然后发出下一个请求,告诉web服务在服务器上处理数据并返回状态响应。

HttpWebRequest processRequest = (HttpWebRequest)WebRequest.Create(baseAddress + processURIRequest);
processRequest.Timeout = 10000;
processRequest.ReadWriteTimeout = 10000;
processRequest.ContentType = "GET";
HttpWebResponse processRequestResponse = (HttpWebResponse)processRequest.GetResponse();
using (Stream processRequestResponseStream = processRequestResponse.GetResponseStream())
{
    //Do stuff...
}

当我更改内容类型时,它适用于XML数据。然而,当我像上面所示那样使用二进制数据时,操作总是超时…即使我将超时时间增加到10秒以上。它正在执行的处理不应该花这么长时间返回。

当我调试时,它总是挂在GetResponse:

那一行
HttpWebResponse processRequestResponse = (HttpWebResponse)processRequest.GetResponse();

WebRequest GetResponse没有响应,操作超时

添加

HttpWebResponse uploadRequestResponse = (HttpWebResponse)uploadRequest.GetResponse();

写入流后解决了此问题。