android发送get请求时报错
异常信息:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.synology.synologycloud/com.synology.synologycloud.MainActivity}: android.os.NetworkOnMainThreadException
第一次看到这异常,字面意思是说:在主线程中的网络异常。然后我就去了解了下这个异常,先看看官方的说明
public classNetworkOnMainThreadException
extends RuntimeExceptionjava.lang.Object | ||||
? | java.lang.Throwable | |||
? | java.lang.Exception | |||
? | java.lang.RuntimeException | |||
? | android.os.NetworkOnMainThreadException |
Class Overview
The exception that is thrown when an application attempts to perform a networking operation on its main thread.
This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it‘s heavily discouraged. See the document Designing for Responsiveness.
Also see StrictMode
.
所以get请求不能在主UI线程中发起,我的解决办法是另外开一个线程,方法如下:
//android中不能再主线程中访问网络资源
new Thread(new Runnable(){
@Override
public void run() {
try {
getOauthToken();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。