Share via


HttpClient GetAsync not working

Question

Friday, February 27, 2015 8:08 PM

Hello expert,

I tried to add Request header in Httpclient and when i call httpclient.GetAsync method it will not doing anything and not returning data in response. However when i ran same code in simple console app (without xamarin project) its working and i can get json response. I am running below code in Android Xamarin project

here is my code

`private static async Task MyProfile() { var baseUrl = "https://api.codeproject.com/";

    var accessToken = "vxLUr5tm0oJX_9ASmeq7bnNJvgS68lAJlNsaK_WIpC-6tjnQMrWBga3POHtZ2LvTsxOdY7xxp9UGRr58kLld5Jg3eXxClzxPj49NQza4xJtBMxWqE2HDCcno4T_4lV6_k21aXRzYDO_8gZa7uZsSFSqrUDjvQZEkehD1WWUSXAaEIbYFzEhYvGSWeknvw4WnzSwuezZqLxGuEtGBQaPyqg9j774xTis3rw4t1LTQXNjuUkfyXwgDzEncUSQzUISj5HbTtB9O2Y-ZJKPb39bR_fWUmItR8zct6YlfDFJ5imW2yQnbJiNogzCRFJbZUd9LUFfPn7oQvAoCV9790PrhH0WJS2JDs54UtdZEeBMMxcm4qhICeQMTzRu6rYBxdGCJVVaSA0R6ZOHs8Mt6mU-J6tn_ZKLhkVX8JmvquB_dJpV0gzfjaUp0tBYvY7IPtillI8_14kaDCnDlUOflmi1iMUDiuESXigqHtRODuWgCLyNZyFIf";

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(baseUrl);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response =null;
            // Add the Authorization header with the AccessToken.
            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
            var numberOfAttempts = 0;
            // create the URL string.
            string url = string.Format("v1/My/Profile");
            do
            {
                try
                {
                     response =  await client.GetAsync(url);
                }
                catch (Exception es)
                {
                    {
                        numberOfAttempts++;
                    }

                }
            } while (numberOfAttempts<4);



            // parse the response and return the data.
            string jsonString = await response.Content.ReadAsStringAsync();
            object responseData = JsonConvert.DeserializeObject(jsonString);

            return 1;
        }`

All replies (5)

Friday, February 27, 2015 11:50 PM

And how do you execute MyProfile? Your code is probably blocking somewhere.


Sunday, March 1, 2015 7:48 AM

Never Mind. Its resolved. Indeed it was deadlock because i used wait() in mainactivity to call this async.

Thanks


Sunday, October 9, 2016 9:36 AM

Thanks Rohit. Had the same problem :)


Thursday, May 4, 2017 12:43 AM

I was facing the same issue, You have to try first run the url from the mobile first. To make sure you device can access the web service.


Friday, May 5, 2017 4:20 PM

Glad you resolved, but for others also be sure you granted the required network permissions in your Android Manifest.