android发送get请求时报错

异常信息:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.synology.synologycloud/com.synology.synologycloud.MainActivity}: android.os.NetworkOnMainThreadException

第一次看到这异常。字面意思是说:在主线程中的网络异常。然后我就去了解了下这个异常,先看看官方的说明

public class

NetworkOnMainThreadException

extends RuntimeException
java.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.

一个APP假设在主线程中请求网络操作。将会抛出此异常。

Android这个设计是为了防止网络请求时间过长而导致界面假死的情况发生。


所以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();

原文地址:https://www.cnblogs.com/cxchanpin/p/7096390.html