android.os.NetworkOnMainThreadException 用于 android 应用
android.os.NetworkOnMainThreadException for android app
我正在尝试调用具有 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 将 return json 数据。但是我收到 android.os.NetworkOnMainThreadException 错误意味着它转到最后一个 catch 语句。
我在 AndroidManifest.xml 文件中设置了
<uses-permission android:name="android.permission.INTERNET"/>
谢谢
当应用程序试图在其主线程上执行网络操作时抛出此异常。 运行 您的代码在 AsyncTask
我正在尝试调用具有 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 将 return json 数据。但是我收到 android.os.NetworkOnMainThreadException 错误意味着它转到最后一个 catch 语句。
我在 AndroidManifest.xml 文件中设置了
<uses-permission android:name="android.permission.INTERNET"/>
谢谢
当应用程序试图在其主线程上执行网络操作时抛出此异常。 运行 您的代码在 AsyncTask