Fix Android’s “Cleartext HTTP traffic not permitted”

When you try connecting to a server via HTTP, the Android Studio shows an exception.

Cannot send data to the server java.net.UnknownServiceException: CLEARTEXT communication to [HOST] not permitted by network security policy

The connection works fine on Android 7 and below. The cause of this problem is that a special security policy is required if the app connects to the server via HTTP instead of HTTPS protocol.

There are 2 ways to address this issue

1) Use HTTPS instead of HTTP

The cause of the problem is the protocol so we can just switch connection’s protocol to https. Using encrypted transfer protocol is recommended.

2) Add exception to the security policy

The most simple way to is add android:usesCleartextTraffic=”true” to application tag in AndroidManifest.xml

<application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:usesCleartextTraffic="true"
            android:theme="@style/AppTheme">
...
</application>

The 2nd option is to use network-security-config. Add network_security_config.xml under src\main\res\xml\.

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">domain or IP</domain>
    </domain-config>
</network-security-config>

And set it in AndroidManifest.xml

<application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:networkSecurityConfig="@xml/network_security_config"
            android:theme="@style/AppTheme">
...
</application>

Leave a Comment

Your email address will not be published. Required fields are marked *


Scroll to Top

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close