android發送get請求時報錯
異常資訊:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.synology.synologycloud/com.synology.synologycloud.MainActivity}: android.os.NetworkOnMainThreadException
第一次看到這異常,字面意思是說:在主線程中的網路異常。然後我就去瞭解了下這個異常,先看看官方的說明
public classNetworkOnMainThreadExceptionextends 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();