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();
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