Search code examples
c#androidxamarinhttpwebrequest

HttpWebRequest: Access denied on release build - Xamarin (Android)


I'm trying to develop a simple app for Android with Xamarin. The app makes a HTTP request to a Web API.

Here is the main code:

            var messageTxt = FindViewById<EditText>(Resource.Id.message);
            var apiUrlTxt = FindViewById<EditText>(Resource.Id.apiurl);

            var url = String.Format("{0}/api/values/{1}", apiUrlTxt.Text, messageTxt.Text);
            var j = await FetchApi(url);

            var apiReturn = FindViewById<TextView>(Resource.Id.apiReturn);
            apiReturn.Text = j;

And here is the FetchApi method:

private async Task<string> FetchApi(string url)
    {
        try
        {
            var request = HttpWebRequest.Create(url);
            request.ContentType = "application/json";
            request.Method = "GET";
            request.Timeout = 10000;

            using (var response = await request.GetResponseAsync())
            {
                using (var s = response.GetResponseStream())
                {
                    return await Task.Run(() => JsonObject.Load(s));
                }
            }
        }
        catch(Exception ex)
        {
            return await Task.Run(() => "Erro - " + ex.Message);
        }
    }

I'm running the app on a external device. Everything works great on the Debug mode, but when I switch to Release, the HttpWebRequest returns an WebException with message "Error: ConnectFailure (Access denied)"

I've already tried to set the Packaging and Linker options the same for the Debug and the Release mode, but the Debug version continues to work, and the Release version continues to fail.

I also tried to set the Linking to None in Release mode, but it also didn't work.

Am I missing something here?


Solution

  • You need to explicitly tell Android that your app can access the Internet by setting the flag in AndroidManifest.xml. When you're in debug mode this is enabled by default, but in release builds you need to specifically set it.