HttpClient.GetStreamAsync() 与自定义请求?

tes*_*ing 3 c# stream portable-class-library dotnet-httpclient xamarin.forms

我的目标是使用HttpClient该类进行网络请求,以便我可以将响应写入文件(解析后)。因此我需要将结果作为Stream.

HttpClient.GetStreamAsync()仅将字符串requestUri作为参数。所以不可能用 custom HttpRequestHeader、 custom HttpMethod、 custom ContentType、 custom content 等来创建请求?

我看到HttpWebRequest有时会使用它,但在我的 PCL(Profile111)中没有Add用于Headers. 那么我可以使用HttpClient,我应该使用HttpWebRequest还是应该使用另一个类/库?

Tod*_*ier 8

GetStreamAsync只是构建和发送无内容 GET 请求的快捷方式。做“长路”是相当简单的:

var request = new HttpRequestMessage(HttpMethod.???, uri);
// add Content, Headers, etc to request
request.Content = new StringContent(yourJsonString, System.Text.Encoding.UTF8, "application/json");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
response.EnsureSuccessStatusCode();
var stream = await response.Content.ReadAsStreamAsync();
Run Code Online (Sandbox Code Playgroud)

  • ~~等待您提供的“SendAsync”调用会导致整个响应被我读入内存。使用 `await client.GetStreamAsync(url);` 允许我在不将整个响应放入内存的情况下传递流。当我在之前和之后对堆进行快照时,我可以在内存中看到所有 60+MB 的下载文件,而在后者中,堆仅增加了 5 MB 左右。~~错过了 HttpCompletionOption! (4认同)