HttpURLConnection with JSON on Android 9, API 28

我正在尝试在Android 9,API 28中使用HttpURLConnection。它适用于Android 8.0.0,API 26,但不适用于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();


            ...

我试图使用以查看哪些代码未执行,我看到它停止在Log.dOutputStream os = urlConnection.getOutputStream();


你知道问题出在哪里吗?


温温酱
浏览 91回答 2
2回答

慕尼黑8549860

试试这个添加Manifest.xmlcleartextTrafficPermitted="true"它看起来像这样 如何允许在Android(9)Pie中的所有网络连接类型HTTP和HTTPS?

汪汪一只猫

这是因为Apache HTTP客户端的折旧,所以在标签中添加下面一行。<uses-library&nbsp;android:name="org.apache.http.legacy"&nbsp;android:required="false"/>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java