0

I have problem: on Android 2 the code below works fine, but on Android 4 doesn't work...

try {
    HttpParams params = new BasicHttpParams(); 
    HttpConnectionParams.setConnectionTimeout(params, 15000); 
    HttpClient client = new DefaultHttpClient(params);  
    String postURL = "http://web.lt/data.php";
    HttpPost post = new HttpPost(postURL);
    List<NameValuePair> paramss = new ArrayList<NameValuePair>();
    paramss.add(new BasicNameValuePair("X", "k"));
    paramss.add(new BasicNameValuePair("Y", "x"));
    paramss.add(new BasicNameValuePair("speed", "xyz"));
    UrlEncodedFormEntity ent = new UrlEncodedFormEntity(paramss,HTTP.UTF_8);
    post.setEntity(ent);
    HttpResponse responsePOST = client.execute(post);  
    HttpEntity resEntity = responsePOST.getEntity();

    if (resEntity != null) {    
        Log.i("RESPONSE",EntityUtils.toString(resEntity));
    }
} catch (Exception e) {
    e.printStackTrace();
}

I tried to download https://code.google.com/p/httpclientandroidlib/ and install right-click on project -> Properties -> Java Build Path -> Libraries -> Add External JARs but when I change:

inport org.apache.http

to

import ch.boye.httpclientandroidlib.HttpEntity;

... the apps crashes.

Trinimon
  • 13,839
  • 9
  • 44
  • 60
Vykintas
  • 401
  • 1
  • 8
  • 23
  • What is the error message? Also, please check your spelling... – theomega Mar 31 '13 at 09:15
  • 1
    You are probably getting a getting a `NetworkOnMainThreadException`, did you? Check out http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception in that case – Trinimon Mar 31 '13 at 09:33
  • Do you perform the connection on the main Thread ? What's the exception thrown ? – Stephane Mathis Mar 31 '13 at 09:15

2 Answers2

2

You must be performing the connection on the Main UI Thread which was allowed in android 2 and above but was discontinued in honeycomb and later. Please See Android AsyncTask

Parvaz Bhaskar
  • 1,367
  • 9
  • 29
1

This is a well known problem. Make the call from an AsyncTask or a Service instead of performing it from the UI thread. Network calls on the UI thread will block the UI and provide a bad user experience. An exception is thrown to avoid this situation in later versions of Android.

Deepak Bala
  • 11,095
  • 2
  • 38
  • 49