简体   繁体   English

用HttpClient替换HttpWebRequest

[英]Replace HttpWebRequest with HttpClient

Due to this reason, https://github.com/dotnet/corefx/issues/11873#issuecomment-470611032 由于这个原因, https://github.com/dotnet/corefx/issues/11873#issuecomment-470611032

I trying to replace HttpWebRequest with HttpClient 我试图用HttpClient替换HttpWebRequest

HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.AllowWriteStreamBuffering = false;

using (var requestStream = await wr.GetRequestStreamAsync().ConfigureAwait(false))
{
    await this.ZipFilesIntoStream(fileEntries, requestStream).ConfigureAwait(false);
}

And I cannot find any guide on how to get the stream with HttpClient. 而且我找不到任何有关如何使用HttpClient获取流的指南。

using (var memoryStream = new MemoryStream())
using (var requestStream = await wr.GetRequestStreamAsync().ConfigureAwait(false))
{
    await HttpClient.PostAsync(url, new StreamContent(memoryStream)
    {
    }).ConfigureAwait(false);

    await this.ZipFilesIntoStream(fileEntries, requestStream).ConfigureAwait(false);
}

The code tries to use HttpClient as if it were HttpWebRequest. 该代码尝试使用HttpClient,就像它是HttpWebRequest一样。 An HttpClient doesn't represent a request though. HttpClient并不代表请求 It's a class that executes different HTTP methods. 这是一个执行不同HTTP方法的类。 The contents should be prepared before calling PostAsync , GetAsync or the generic SendAsync 应该调用PostAsyncGetAsync或通用SendAsync 之前准备内容

I assume that ZipFilesIntoStream packages files into a stream. 我假设ZipFilesIntoStream文件打包到流中。 Since a MemoryStream is also available, it should use it as its storage : 由于MemoryStream也可用,因此应将其用作存储设备:

using (var memoryStream = new MemoryStream())
{
    await ZipFilesIntoStream(fileEntries, memoryStream);
    memoryStream.Position=0;
    await client.PostAsync(url, new StreamContent(memoryStream));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM