我正在尝试在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"
它看起来像这个How to allow all Network connection types HTTP and HTTPS in Android (9) Pie?
这是因为Apache HTTP客户端折旧,所以在标记中添加以下行。
<uses-library android:name="org.apache.http.legacy" android:required="false"/>