Search code examples
androidhttpwebrequestcompatibilityandroid-compatibility

Android: Http request doesn't work on 4.0


I tested this code and it works fine on 2.2 and 2.3.3, but it crashes on 4.0.

The problem seems to be with the http request. Any ideas why?

public class Rezultat extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity);

    //http post
    InputStream is=null;
    try{

            String url="http://google.com";
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
    }catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
    }
    //convert response to string
    try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
            }
            is.close();

            result=sb.toString();

    }catch(Exception e){
            Log.e("log_tag", "Error converting result "+e.toString());
    }

Solution

  • e.printstacktrace() will tell you:

    http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

    The exception that is thrown when an application attempts to perform a networking operation on its main thread.

    This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged. See the document Designing for Responsiveness.

    private class DownloadFromUrlTask extends AsyncTask<String, Void, Bitmap> {
    
        protected void onPreExecute() {
            mDialog = ProgressDialog.show(ChartActivity.this,"Please wait...", "Retrieving data ...", true);
        }
    
        protected String doInBackground(String... urls) {
            //All your network stuff here.
            return result
        }
    }