问题
My goal is to use the HttpClient class to make a web-request so that I can write the response to a file (after parsing). Therefore I need the result as a Stream.
HttpClient.GetStreamAsync() only takes the string requestUri as parameter. So there is no possibility to create a request with custom HttpRequestHeader, custom HttpMethod, custom ContentType, custom content and so on?
I saw that HttpWebRequest is sometimes used instead, but in my PCL (Profile111) there is no Add method for the Headers. So can I use HttpClient, should I use HttpWebRequest instead or should I use another class/library at all?
回答1:
GetStreamAsync is just a shortcut for building and sending a content-less GET request. Doing it the "long way" is fairly straightforward:
var request = new HttpRequestMethod(HttpMethod.???, uri);
// add Content, Headers, etc to request
var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
response.EnsureSuccessStatusCode();
var stream = await response.Content.ReadAsStreamAsync();
回答2:
Since you mentioned being open to using a different library, here's an alternative that uses Flurl (disclaimer: I'm the author). Say you want to POST some JSON data with a couple custom headers and receive a stream:
var stream = await "https://api.com"
.WithHeaders(new { header1 = "value1", header2 = "value2" })
.PostJsonAsync(data)
.ReceiveStream();
Here data is just a POCO. Don't worry about serializing it to a JSON string or setting Content-Type to application/json; Flurl will do both for you.
Flurl uses HttpClient under the hood and targets .NET Standard 1.1, which is fully compatible with PCL Profile111.
来源:https://stackoverflow.com/questions/47513400/httpclient-getstreamasync-with-custom-request