Search code examples
c#xamarinxamarin.formshttpwebrequest

Xamarin.Forms HttpWebResponse Hangs / Freezes


I got a problem with my HttpWebResponse object inside my Task<T>

public async Task<string> Get(string url)
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(urlAddress);
        WebRequest request = WebRequest.Create(url);

        Debug.WriteLine($"CHECKING 5000");

        using (var resp = (HttpWebResponse)await request.GetResponseAsync() as HttpWebResponse)
        {
            Debug.WriteLine($"CHECKING 10000");

            if (resp.StatusCode == HttpStatusCode.OK)
            {
                //var json = await result.Content.ReadAsStringAsync();
                //status = JsonConvert.DeserializeObject<MyResultObject>(json);

                Debug.WriteLine($"CHECKING = {resp.StatusCode}");
            }
        }
    }

    return "";
}

I have a number of Debug.WriteLine()'s is here to easily see what part my code gets to.

I can see Debug.WriteLine($"CHECKING 5000");
I cannot see Debug.WriteLine($"CHECKING 10000");

I can access the website in a browser fine, so I am not sure what the issue here.

What can I do to see why it is doesn't work and then fix it?


Solution

  • Try this

    public async Task<string> Get(string url)
    {
    
        Debug.WriteLine($"CHECKING 5000");
    
        using (var client = new HttpClient())
        {
            Debug.WriteLine($"CHECKING 10000");
    
            var resp = await client.GetAsync (url);
    
            //you can replace the if below with response.IsSuccessStatusCode
            if (resp.StatusCode == HttpStatusCode.OK)
            {
                Debug.WriteLine($"CHECKING = {resp.StatusCode}");
            }
    
        }
    
        return String.Empty;
    }