1

I'm running a POST request to an API during a login within my Android app to get the user's information and verify their account exists. There's a NetworkOnMainThreadException that's coming my way when I try to do this.

logger.log(Level.INFO, "POST request URL: "+this.getUrl());
URL url = new URL(this.getUrl());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
logger.log(Level.INFO, "Connection open");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setUseCaches(false);

OutputStream outputStream = connection.getOutputStream();
DataOutputStream wr = new DataOutputStream(outputStream); //ERROR HAPPENS HERE

The exception actually has a null error message. With research on this exception I've seen that it appears to be a threading issue where I'm running the UI on the same thread as this POST request. Is this true?

I've done this same method on a web-based application running on Glassfish and it worked fine.

Ben
  • 60,438
  • 111
  • 314
  • 488
  • 1
    You could do this, although it was always bad, prior to API 11. The reason is that doing network stuff on the main UI thread blocks the UI and can lead to an ANR (Application Not Responding) error. To enforce this, API 11 throws the exception you're seeing if any network activity is attempted on the main thread. It's an Android thing (android.os.NetworkOnMainThreadException), not a Java thing, therefore no parallel on Glassfish. – Simon Jan 01 '13 at 21:35

1 Answers1

5

Yes, it is true. Running IO stuff in the GUI thread is not a good idea, with regards to responsiveness. That's why Android is throwing the NetworkOnMainThreadException, if you try to do network operations in the GUI thread. See also this blog post of why this exception is thrown.

The solution to this is simple, do your network operations in a separate thread with AsyncTask.

Community
  • 1
  • 1
Aleksander Blomskøld
  • 18,374
  • 9
  • 76
  • 82