Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

HttpURLConnection connecting to a localhost works on Android 7 but not on Android 10

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();
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading