When I try to connect to the network on the UI thread (mainactivity), the runtime throws an exception droid.os.NetworkOnMainThreadException
The official Android document says
The exception is thrown when an application attempts to perform a networking operation on its main thread.
This is a thrown for applications targeting the honeycomb SDK or higher. Applications targeting earlier SDK versions is allowed to does networking on their main event loop threads, but it's heavil Y discouraged. See the document designing for responsiveness.
Based on the consideration of reducing the time-consuming operation of the UI thread, Android over 3.0 no longer allows network connectivity on the UI thread.
Workaround
1. Use strict Mode to force the connection to the UI thread (not recommended by the official)
2. Open a thread for the network connection, and then use handler to pass the result to the UI thread.
Android.os.NetworkOnMainThreadException Exception Handling