0

recently I'm having problem in HttpUrlConnection with Android 9.0 in my Huawei Mate 10. I'm using HttpUrlConnection to check my phone's connection status, but when comes to HttpUrlConnection .connect, it shows me Failed to Connect to [My Server URL].

Here is my code

URL url = new URL(appPrefs.getServerUrl());
            Log.e("Url :", appPrefs.getServerUrl());
                HttpURLConnection urlc = (HttpURLConnection) url
                        .openConnection();
                urlc.setConnectTimeout(5 * 1000);
                urlc.connect();

                return (urlc.getResponseCode() == 200)
                        ? Boolean.TRUE
                        : Boolean.FALSE;

The error occurred at this line :

urlc.connect();

The Error:

java.net.ConnectException: Failed to connect to

Any help will be appreciated.

Leon kong
  • 121
  • 1
  • 2
  • 9

1 Answers1

-1

Also have a look at - https://koz.io/android-m-and-the-war-on-cleartext-traffic/

  • Option 1 -

Create file res/xml/network_security_config.xml -

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">Your URL(ex: 127.0.0.1)</domain>
    </domain-config>
</network-security-config>

AndroidManifest.xml -

<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        ...
        android:networkSecurityConfig="@xml/network_security_config"
        ...>
        ...
    </application>
</manifest>
  • Option 2 -

AndroidManifest.xml -

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

Also as @david.s' answer pointed out android:targetSandboxVersion can be a problem too -

According to Manifest Docs -

android:targetSandboxVersion

The target sandbox for this app to use. The higher the sandbox version number, the higher the level of security. Its default value is 1; you can also set it to 2. Setting this attribute to 2 switches the app to a different SELinux sandbox. The following restrictions apply to a level 2 sandbox:

The default value of usesCleartextTraffic in the Network Security Config is false. Uid sharing is not permitted.

  • So Option 3 -

If you have android:targetSandboxVersion in then reduce it to 1

AndroidManifest.xml -

<?xml version="1.0" encoding="utf-8"?>
<manifest android:targetSandboxVersion="1">
    <uses-permission android:name="android.permission.INTERNET" />
    ...
</manifest>

copy from Android 8: Cleartext HTTP traffic not permitted

Smirk test
  • 50
  • 6