Home > Back-end >  HttpURLConnection connecting to a localhost works on Android 7 but not on Android 10
HttpURLConnection connecting to a localhost works on Android 7 but not on Android 10

Time:02-01

This is a simple code sample that I use to write/read a message to/from a localhost. I tested on an Android emulator. It works on Android 7 but not on Android 10. On Android 10, I found the program hangs on conn.getOutputStream(). How can I update my code to make it work on Android 10?

URL url = null;
HttpURLConnection conn = null;
try {
   url = new URL("http://10.0.2.2:3016/");
   conn = (HttpURLConnection) url.openConnection();
   conn.setDoOutput(true);
   conn.setDoInput(true);
   conn.setRequestMethod("POST");
   conn.setChunkedStreamingMode(0);
   try(BufferedWriter bw  = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()))) {
       bw.write("some messages...");
   }
   StringBuilder sb = new StringBuilder();
   try(BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
      String line = null;
      while((line = br.readLine()) != null) {
         sb.append(line);
      }
   }
} catch (Exception e) {
   e.printStackTrace();
}

CodePudding user response:

Since API-28 (Android 8.0), HTTP is not permitted by default. (See Network security configuration.)

You must permit CleartextTraffic explicitly when you use HTTP other than HTTPS.

Manifest.xml:

<application android:networkSecurityConfig="@xml/network_security_config">

res/xml/network_security_config.xml:

<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">10.0.2.2</domain>
    </domain-config>
</network-security-config>
  •  Tags:  
  • Related