All Things Techie With Huge, Unstructured, Intuitive Leaps

Android App Development -- Getting HTTP Post to Work

This could be titled: "How To Make HTTP Get Request To Server - Android Example", or it could be titled "Android HTTP Post Error", or it could be titled "How to overcome a stubborn exception trying to programatically make a call to a server".  Or it could simply be called "HTTP Nut Crush".  OK, kiddie scripters, the internet is full of examples how to use an http client in Android to post to a server -- right?  Right!

Here's the code:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.wasteTime.com?data=crap")
try {    
      // Execute HTTP Post Request  
      HttpResponse response = httpclient.execute(httppost);  
      Log.w("HTTP Response", response.getStatusLine().toString());

    } catch (Exception e) { 

    }

 Piece of cake.  However the f*&K*ing thing doesn't work.  I tried putting in Log.w("Message", e.getMessage()) in the catch block, and it threw a Null Pointer exception.  Get stacktrace didn't work.
Finally in frustration, I put in e.printStackTrace() and I got this jolly frigging error:

02-14 14:50:53.440: W/System.err(10005): android.os.NetworkOnMainThreadException
02-14 14:50:53.440: W/System.err(10005): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1077)

Obviously I was violating some new turdlet policy that wouldn't let me make the call to the server. 

So what to do?

It turns out that the answer was simple.  You cannot do networking stuff on the main UI thread in Honeycomb SDK and higher.  To fix it, you have to kick a new thread.  Here is the working code.

new Thread(new Runnable() {

 public void run() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.wasteTime.com?data=crap")
try {    
      // Execute HTTP Post Request  
      HttpResponse response = httpclient.execute(httppost);  
      Log.w("HTTP Response", response.getStatusLine().toString());

    } catch (Exception e) {  e.printStackTrace();
}
}
 }).start();

Hope this helps someone.

No comments:

Post a Comment