HTTP doesn't work in Android emulator

后端 未结 3 2058
故里飘歌
故里飘歌 2020-12-01 17:20

I tried multiple HTTP classes (HttpURLConnection, HTTPClient and others) but they don\'t work in emulator. Then I decided to test that on my phone

3条回答
  •  一个人的身影
    2020-12-01 17:24

    If you look at this Android documentation, it explains

    NetworkOnMainThreadException:

    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.

    So, depending on OS version, there may be enforcement (exception throwing) of the policy that you not make network requests on the UI thread. This could explain why your code works on a device, and not on an emulator (if they have different Android versions).

    You could change the ThreadPolicy. But as an alternative, I'd suggest you look again at the statement in the Android docs. They heavily discourage performing network operations on the main thread, and I'd certainly agree with them.

    So, rather than changing the policy to make it legal, you might consider changing your code, so that your getResponse() method is not called on the UI thread.

    Typically, you would use AsyncTask to do the work in the background.

提交回复
热议问题