Search code examples
c#xamarin.formsstreamportable-class-librarydotnet-httpclient

HttpClient.GetStreamAsync() with custom request?


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?


Solution

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