任何人都有示例代码,可以直接将一个Web的"分块"HTTP流式下载内容上传到单独的Web服务器吗?

Gre*_*reg 5 c# streaming http httpwebrequest chunked-encoding

背景 - 我正在尝试使用C#中的HttpWebRequest/HttpWebResponse将现有网页流式传输到单独的Web应用程序.我引人注目的一个问题是我正在尝试使用文件下载的内容长度来设置文件上载请求内容长度,但是当源网页位于HttpWebResponse不具有的Web服务器上时,问题似乎就出现了问题.提供内容长度.

HttpWebRequest downloadRequest = WebRequest.Create(new Uri("downloaduri")) as HttpWebRequest;
 using (HttpWebResponse downloadResponse = downloadRequest.GetResponse() as HttpWebResponse)
 {
   var uploadRequest = (HttpWebRequest) WebRequest.Create(new Uri("uripath"));
   uploadRequest.Method = "POST";
   uploadRequest.ContentLength = downloadResponse.ContentLength;  // ####
Run Code Online (Sandbox Code Playgroud)

问题:我如何更新此方法以满足此情况(当下载响应没有设置内容长度时).是不是以某种方式使用MemoryStream呢?任何示例代码将不胜感激. 特别是有一个代码示例,有人会说,如何进行"分块"HTTP下载和上传,以避免源Web服务器的任何问题不提供内容长度?

谢谢

fer*_*oze 5

正如我已经在Microsoft论坛中应用的那样,您有几个选项.

但是,我是这样做的MemoryStream:

HttpWebRequest downloadRequest = WebRequest.Create(new Uri("downloaduri")) as HttpWebRequest;

byte [] buffer = new byte[4096];
using (MemoryStream ms = new MemoryStream())
using (HttpWebResponse downloadResponse = downloadRequest.GetResponse() as HttpWebResponse)
{
    Stream respStream = downloadResponse.GetResponseStream();
    int read = respStream.Read(buffer, 0, buffer.Length);

    while(read > 0)
    {
        ms.Write(buffer, 0, read);
        read = respStream.Read(buffer, 0, buffer.Length);
    }

    // get the data of the stream
    byte [] uploadData = ms.ToArray();

    var uploadRequest = (HttpWebRequest) WebRequest.Create(new Uri("uripath"));
    uploadRequest.Method = "POST";
    uploadRequest.ContentLength = uploadData.Length;

    // you know what to do after this....
}
Run Code Online (Sandbox Code Playgroud)

另外,请注意,您实际上不需要担心知道ContentLength先验值.正如您所猜测的那样,您可以将其设置SendChunkedtrueon uploadRequest,然后将其从下载流复制到上载流中.或者,你可以在没有设置的情况下进行复制chunked,并且HttpWebRequest(据我所知)将在内部缓冲数据(确保AllowWriteStreamBuffering设置为trueon uploadrequest)并找出内容长度并发送请求.