HttpURLConnection with JSON on Android 9, API 28

user3566569 :

I'm trying to use HttpURLConnection in Android 9, API 28. It works on Android 8.0.0, API 26, but not on API 28.

            JSONObject jsonObject = new JSONObject();
            jsonObject.accumulate("name", name);
            String json = jsonObject.toString();

            URL url = new URL("http://website_link");
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoOutput(true);
            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

            OutputStream os = urlConnection.getOutputStream();
            os.write(json.getBytes("UTF-8"));
            os.close();

            InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("utf-8")), 8);
            String line;
            json = "";

            while ((line = reader.readLine()) != null) {
                json += line;
            }

            inputStream.close();

            jsonObject = new JSONObject(json);

            inputStream.close();
            urlConnection.disconnect();

            ...

I tried to use Log.d to see what code is not executed and I saw that it stops on OutputStream os = urlConnection.getOutputStream();

Do you know where is the problem?

Hasan Kucuk :

Try this add Manifest.xml

cleartextTrafficPermitted="true"

it look like this How to allow all Network connection types HTTP and HTTPS in Android (9) Pie?

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=158532&siteId=1