背景- 我正在尝试使用 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; // ####
QUESTION:我如何更新此方法来满足这种情况(当下载响应没有设置内容长度时)。也许会以某种方式使用 MemoryStream 吗?任何示例代码将不胜感激。特别是,是否有一个代码示例可以展示如何进行“分块”HTTP 下载和上传,以避免源 Web 服务器不提供内容长度的任何问题?
Thanks
正如我已经在 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
先验。正如您所猜测的,您可以设置SendChunked
to true
on uploadRequest
,然后从下载流复制到上传流。或者,您可以直接进行复制而不进行设置chunked
, and HttpWebRequest
(据我所知)将在内部缓冲数据(确保AllowWriteStreamBuffering
被设定为true
on uploadrequest
)并计算出内容长度并发送请求。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)