Search code examples
androidandroid-4.0-ice-cream-sandwich

Android HTTPRequest on ICS fails :(


Here is my sample code to make http request but it fails to do so. Here is the error log i see in LogCat. http://pastebin.com/56AL8Dxu I have also added <uses-permission android:name="android.permission.INTERNET"></uses-permission> in manifest. Please help me..is that really that hard to make a simple http request in Android ? I am from .Net background learning Android development.

void testHTTP()
 {
  HttpClient httpClient = new DefaultHttpClient();

  HttpUriRequest request = new HttpPost("http://www.google.com");

  try {
   HttpResponse response = httpClient.execute(request);

   //System.out.println("response protocol version: " + response.getProtocolVersion());
  } catch (ClientProtocolException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }

Solution

  • As stated in the Logcat log:

    04-29 19:59:53.072: E/AndroidRuntime(546): android.os.NetworkOnMainThreadException

    You perform testHTTP(), which involves networking on main thread, which is not allowed. Move it to a background thread, or use AsyncTask.