Java Android 9上带JSON的HttpURLConnection,API 28
我正在尝试在Android 9、API 28中使用HttpURLConnection。它适用于Android 8.0.0、API 26,但不适用于API 28Java Android 9上带JSON的HttpURLConnection,API 28,java,android,json,httpurlconnection,Java,Android,Json,Httpurlconnection,我正在尝试在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 u
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客户端折旧,
因此,将下面的一行添加到
标签
谢谢,我在AndroidManifest.xml中的应用程序标记中添加了android:usesCleartextTraffic=“true”,它可以正常工作!我在导入这些库时出错,无法解析此HTTPurlConnection not Found。我试图添加该标记,但它不起作用。Hasan Kucuk提出的添加ClearTextTrafficAllowed=“true”的解决方案有效。这“不起作用”是怎么回事?崩溃意外行为?正如我所写,它在OutputStream os=urlConnection.getOutputStream()上停止;。那个部分并没有执行,什么也并没有发生,应用程序并没有崩溃,只是那个部分并没有执行。
<uses-library android:name="org.apache.http.legacy" android:required="false"/>