2

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?

user3566569
  • 109
  • 2
  • 9
  • How is this "not working"? Crash? Unexpected behavior? – tir38 Mar 28 '19 at 02:21
  • As I wrote it stops on OutputStream os = urlConnection.getOutputStream();. That part is not executed and nothing happens, app doesn't crash, just that part is not executed. – user3566569 Mar 28 '19 at 13:09

2 Answers2

1

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?

Hasan Kucuk
  • 2,433
  • 6
  • 19
  • 41
0

This is because of Apache HTTP client depreciation , So add the below line in tag.

<uses-library android:name="org.apache.http.legacy" android:required="false"/>
Saurav Kumar
  • 891
  • 8
  • 14
  • I tried to add that tag and it didn't worked. Solution by Hasan Kucuk to add cleartextTrafficPermitted="true" worked. – user3566569 Mar 27 '19 at 22:20