Search code examples
androidhttpurlconnection

"Cleartext HTTP traffic to www.android.com not permitted" when trying httpurlconnection in Android Studio


I am getting the error in the title line. I have tried to overcome it by trying the suggestions I have found at stack overflow including adding to AndroidManifest.xml this:

android:networkSecurityConfig="@xml/network_security_config"

and then creating res/xml/network_security_config.xml containing this:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
    <domain includeSubdomains="true">www.android.com</domain>
</domain-config>
</network-security-config>

For reference the calling code in the Activity is as follows:

try {
       url = new URL("http://www.android.com/");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    HttpURLConnection urlConnection = null;
    try {
        urlConnection = (HttpURLConnection) url.openConnection();
   

but no luck so far. My goal is to make a simple connection here as a test. How to fix this? TIA.


Solution

  • Add this to you app

    <?xml version="1.0" encoding="utf-8"?>
    <manifest ...>
        <uses-permission android:name="android.permission.INTERNET" />
            <application
                ...
                android:usesCleartextTraffic="true" // this line.
                ...>
                ...
            </application>
     </manifest>