stableboy

 

(转)HttpWebRequest中的SendChunked

 

https://www.bbsmax.com/A/x9J2OwQV56/

 

MSDN上说:When SendChunked is true, the request sends data to the Internet resource in segments. The Internet resource must support receiving chunked data.

传统的send request的方式是在request的header头添加ContentLength,然后把内容写在request的body中写入要发送的内容。而如果用了SendChunked的之后,就不用在header中规定ContentLength了。

往更深层次里说,其实SendChunked模式是在客户端和服务器端建立了一个管道,字节流(其实是segment)通过这个管道发送到服务端。

最近有幸同时接触到服务端和客户端,对这个有了更具体的了解,尤其在代码层面上:

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
// http://www.cnblogs.com/AllanDragoon/p/3323370.html
request.KeepAlive = false;
request.ServicePoint.Expect100Continue = false;
request.AllowWriteStreamBuffering = false;

// Turn on support for GZipped response
request.AutomaticDecompression = DecompressionMethods.GZip;
// Request content type
request.ContentType = "application/octetstream";
// Request accept type
request.Accept = "application/xml";
// Set method
request.Method = method;
// 设置SendChunked为true而不必设ContentLength, 反之亦然
request.SendChunked = true;

using (var requestStream = request.GetRequestStream())
{
StreamUtil.CopyStream(stream, requestStream);
}

using (var response = request.GetResponse())
{

}

通过同时调试客户端和服务端代码,我发现,如果设SendChunked为true,那么当调用request.GetRequestStream的时候,客户端会和服务端通信(我想可能是客户端需呀和服务端建立管道连接);如果为false,则不会和服务端通信。

目前我还不知道如何在服务器端实现支持SendChunked。至少明白了当调用request.GetRequestStream的时候,客户端会和服务端通信。

posted on 2019-08-27 10:48  陌翔  阅读(691)  评论(0编辑  收藏  举报

导航