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
This happens because you try to perform network activity on the main thread.
I had the same issue, It worked for a while, then after a few weeks of developing, it stopped working.
The solution I found was to add these lines to the
onCreate()
Method:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Hope this works for you too
EDIT
Due to increasing number of upvotes, I wish to add something.
This will remove the NetworkingOnMainThreadException, HOWEVER, it is by far not a recommended way.
This exception is there for a reason. Network activity can take time, performing networking on the main thread, which is the same thread that responsible for updating the UI, would freeze the thread until the networking is done (this is what happens on every thread, but when it's performed on a dedicated thread, it's ok). In Android, if the UI-thread isn't active for 5 seconds, it will show the Application is not responsive, Do you want to close it? dialog.
This is what the exception has come to prevent. Setting the policy, like I suggested, while removes the exception, is the wrong way of doing things.
Any networking actions should be done on a separate thread, either by using AsyncTask or by creating new Thread manually. AsyncTask are a very easy and straight-forward way of implementing this, and this is what I recommend.
Please take this edit into consideration when using my answer.
Cheers