复制 Http 请求输入流

2024-01-17

我正在实现一个代理操作方法,该方法转发传入的 Web 请求并将其转发到另一个网页,并添加一些标头。该操作方法适用于 GET 请求的文件,但我仍在努力转发传入的 POST 请求。

问题是我不知道如何正确地将请求正文写入传出的 HTTP 请求流。

这是我到目前为止所得到的内容的简化版本:

//the incoming request stream
var requestStream=HttpContext.Current.Request.InputStream;
//the outgoing web request
var webRequest = (HttpWebRequest)WebRequest.Create(url);
...

//copy incoming request body to outgoing request
if (requestStream != null && requestStream.Length>0)
            {
                long length = requestStream.Length;
                webRequest.ContentLength = length;
                requestStream.CopyTo(webRequest.GetRequestStream())                    
            }

//THE NEXT LINE THROWS A ProtocolViolationException
 using (HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse())
                {
                    ...
                }

当我对传出的 http 请求调用 GetResponse 时,我会收到以下异常:

ProtocolViolationException: You must write ContentLength bytes to the request stream before calling [Begin]GetResponse.

我不明白为什么会发生这种情况,因为 requestStream.CopyTo 应该负责写入正确数量的字节。

任何建议将不胜感激。

Thanks,

Adrian


是的,.Net 对此非常挑剔。解决问题的办法就是同时flushand关闭流。换句话说:

Stream webStream = null;

try
{
    //copy incoming request body to outgoing request
    if (requestStream != null && requestStream.Length>0)
    {
        long length = requestStream.Length;
        webRequest.ContentLength = length;
        webStream = webRequest.GetRequestStream();
        requestStream.CopyTo(webStream);
    }
}
finally
{
    if (null != webStream)
    {
        webStream.Flush();
        webStream.Close();    // might need additional exception handling here
    }
}

// No more ProtocolViolationException!
using (HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse())
{
    ...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

复制 Http 请求输入流 的相关文章

随机推荐