HttpClient hangs for large request

2.5k Views Asked by At

I have an issue in an app developed for Windows Phone 8.1, where its working just fine, but in Windows Mobile 10 it gets stuck on GetAsync. It doesn't throw an exception or anything, just gets stuck there waiting endlessly. The content-length of the response is 22014030 bytes.

using (HttpClient client = new HttpClient())
{
    using (HttpResponseMessage response = await client.GetAsync(url))
    {
        response.EnsureSuccessStatusCode();
        using (HttpContent content = response.Content)
        {
             return await content.ReadAsStringAsync();
        }
    }
}

I have also tried reading it as a stream, but as soon as i try to read the content body nothing happens anymore.

The code that calls this function is declared as:

 public async Task<List<APIJsonObject>> DownloadJsonObjectAsync()
    {
        string jsonObjectString = await DownloadStringAsync(Constants.URL);

        if (jsonObjectString != null && jsonObjectString.Length >= 50)
        {
            List<APIJsonObject> result = await Task.Run<List<APIJsonObject>>(() => JsonConvert.DeserializeObject<List<APIJsonObject>>(jsonObjectString));

            return result;
        }

        return null;
    }
1

There are 1 best solutions below

6
MrCSharp On

The reason it is blocking is because you are getting a huge response (20.9MB) which the HttpClient will try to download before giving you a result.

However, you can tell the HttpClient to return a result as soon as the response headers are read from the server, which means you get a HttpResponseMessage faster. To do this, you will need to pass HttpCompletionOption.ResponseHeadersRead as a parameter to the SendRequestAsync method of the HttpClient

Here is how:

using (var client = new HttpClient())
{
    using (var request = new HttpRequestMessage(new HttpMethod("GET"), url))
    {
        using (var response = await client.SendRequestAsync(request, HttpCompletionOption.ResponseHeadersRead)
        {
          //Read the response here using a stream for example if you are downloading a file
          //get the stream to download the file using: response.Content.ReadAsInputStreamAsync()
        }
    }
}