c# - 任何人都有示例代码,用于将一个网站的 "chunked"HTTP 流式下载直接上传到单独的 Web 服务器?

标签 c# http httpwebrequest streaming chunked-encoding

背景 - 我正在尝试使用 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 服务器不提供内容长度的任何问题?

谢谢

最佳答案

正如我已经在 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 的值。如您所料,您可以在 uploadRequest 上将 SendChunked 设置为 true,然后将其从下载流复制到上传流。或者,您可以在不设置 chunked 的情况下进行复制,HttpWebRequest(据我所知)将在内部缓冲数据(确保 AllowWriteStreamBufferinguploadrequest 上设置为 true)并计算出内容长度并发送请求。

关于c# - 任何人都有示例代码,用于将一个网站的 "chunked"HTTP 流式下载直接上传到单独的 Web 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1868279/

相关文章:

c# - Webresponse 对象出现 (500) 内部服务器错误

c# - 如何在 c# WPF 应用程序中取消上传

c# - HttpWebRequest C# 的 API 超时错误 |与 postman 和 restsharp 一起工作

c# - 具有多泛型问题的 AppDomain.DoCallBack()

ruby-on-rails - RSpec.configure 和请求对象

c# - 创建 float 时出现意外符号 'public'

ruby - 使用 Ruby 的 HTTP 服务器

python - 为什么 python 套接字不能解析带有 http 的 url

c# - Team Foundation Server 不会构建,因为 nuget 包不存在

c# - 如何在 C# 中找到已安装应用程序的升级代码?