连接到本地主机的 HttpURLConnection 在 Android 7 上有效,但在 Android 10 上无效

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

这是我用来 write/read 消息 to/from 本地主机的简单代码示例。我在 Android 模拟器上进行了测试。它适用于 Android 7,但不适用于 Android 10。在 Android 10,我发现程序在 conn.getOutputStream() 上挂起。如何更新我的代码以使其在 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();
}

由于 API-28 (Android 8.0),默认情况下不允许 HTTP。 (参见 Network security configuration。)

当您使用除 HTTPS 以外的 HTTP 时,您必须明确允许 CleartextTraffic

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>