Android 9 上 JSON 的 HttpURLConnection,API 28
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.d
来查看未执行的代码,我看到它停止在 OutputStream os = urlConnection.getOutputStream();
你知道问题出在哪里吗?
试试这个添加 Manifest.xml
cleartextTrafficPermitted="true"
看起来像这样
这是因为 Apache HTTP 客户端折旧,
所以添加以下行
标签。
<uses-library android:name="org.apache.http.legacy" android:required="false"/>
我正在尝试在 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.d
来查看未执行的代码,我看到它停止在 OutputStream os = urlConnection.getOutputStream();
你知道问题出在哪里吗?
试试这个添加 Manifest.xml
cleartextTrafficPermitted="true"
看起来像这样
这是因为 Apache HTTP 客户端折旧, 所以添加以下行 标签。
<uses-library android:name="org.apache.http.legacy" android:required="false"/>