HttpClient.GetStreamAsync() with custom request?

Viewed 5174

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?

2 Answers

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 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();

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.

Related