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