An error is reported when android sends a get request.
Exception information:
Java. lang. RuntimeException: Unable to start activity ComponentInfo {com. synology. synologycloud/com. synology. synologycloud. MainActivity}: android. OS. NetworkOnMainThreadException
The first time you see this exception, it literally means that the network in the main thread is abnormal. Then I learned about this exception. Let's take a look at the official instructions.
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 seeStrictMode.
If an APP requests network operations in the main thread, this exception is thrown. Android is designed to prevent the interface from being suspended due to a long network request time.
Therefore, the get request cannot be initiated in the main UI thread. My solution is to open another thread by using the following method:
// Network resources cannot be accessed in the main thread in 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 ();