An error is reported when android sends a get request.

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.