背景 - 我正在尝试使用 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
(据我所知)将在内部缓冲数据(确保 AllowWriteStreamBuffering
在 uploadrequest
上设置为 true
)并计算出内容长度并发送请求。
关于c# - 任何人都有示例代码,用于将一个网站的 "chunked"HTTP 流式下载直接上传到单独的 Web 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1868279/