简体   繁体   中英

How to get data deserialized using Windows.Web.HttpClient?

I need to get list of objects deserialized from Json.

My problem is that this code hangs in line responseMessage = await httpClient.GetAsync(uri); I have checked get and response in Fiddler, I am getting Json in Fiddler, everything has code 200 OK, but for some reason code do not move forward to next line while debuging in VS or not, it just hangs forever. What I lack in this code to get list of objects?

Since code hangs in mentioned line issue must be somewhere in HttpClient.

using (HttpClient httpClient = new HttpClient())
            {
                try
                {
                    var headers = httpClient.DefaultRequestHeaders;

                    HttpResponseMessage responseMessage;

                    responseMessage = await httpClient.GetAsync(uri);
                    responseMessage.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/x-www-form-urlencoded; charset=UTF-8");

                    var content = responseMessage.Content.ReadAsStringAsync();


                    tvChannelList = JsonConvert.DeserializeObject<List<TvChannels>>(content.GetResults());

                    return tvChannelList;
                }
                catch (Exception ex)
                {
                    throw;
                }
            }

Thanks in advance for any hints.

Problem was so miserable stupid, I forgot to put await before method name that calls for data from web service, thus blocking UI.

before

ListOfTvChannels = _remoteController.GetChannelListAsync();

after

ListOfTvChannels = await _remoteController.GetChannelListAsync();

Thanks all for trying to help.

I use this method when using the HttpClient and want to return an object from a JSON response.

    public async Task<TResult> MakeGetRequest<TResult>(string uri)
    {
        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
            client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Charset", "ISO-8859-1");

            HttpResponseMessage response = await client.GetAsync(uri);
            response.EnsureSuccessStatusCode();
            var data = await response.Content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<TResult>(data);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM