5

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

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;  // ####

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

谢谢

4

1 回答 1

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....
}

另外,请注意,您真的不必担心知道ContentLength先验的价值。如您所料,您可以设置SendChunkedtrueon uploadRequest,然后从下载流中复制到上传流中。或者,您可以在不设置的情况下进行复制chunked,并且HttpWebRequest(据我所知)将在内部缓冲数据(确保AllowWriteStreamBuffering设置为trueon uploadrequest)并计算出内容长度并发送请求。

于 2009-12-08T20:36:00.073 回答