我正在尝试调用一个包含json数据的url。
String response = null;
try {
URL url = new URL("https://demorul.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(10000);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", "application/json;odata=verbose");
conn.setRequestProperty("Accept", "application/json;odata=verbose");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
url将返回json数据。但我得到android.os.NetworkOnMainThreadException错误意味着它转到最后一个catch语句。
在AndroidManifest.xml文件中,我已经设置了
<uses-permission android:name="android.permission.INTERNET"/>
由于
答案 0 :(得分:1)
当应用程序尝试在其主线程上执行网络操作时,抛出此异常。在AsyncTask