用HttpClient替换HttpWebRequest

时间:2019-06-13 15:46:42

标签: c# .net-core dotnet-httpclient

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

我试图用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);
}

我找不到任何有关如何使用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);
}

1 个答案:

答案 0 :(得分:1)

代码试图像使用HttpWebRequest一样使用HttpClient。 HttpClient并不代表 request 。这是一个执行不同HTTP方法的类。内容应在调用PostAsyncGetAsync或通用SendAsync

之前 准备

我假设ZipFilesIntoStream将文件打包到流中。由于MemoryStream也可用,因此应将其用作存储空间:

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