Q:

HTTP Response in Android - NetworkOnMainThreadException

I want to check the HTTP response of a certain URL before loading into a webview. I only want to load webview if http response code is 200. This is a workaround for intercepting http errors. I have below:
HttpGet httpRequest = new HttpGet( "http://example.com");
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httpRequest);
int code = response.getStatusLine().getStatusCode();

But I encountered the following error:
java.lang.RuntimeException: Unable to start activity ComponentInfo
android.os.NetworkOnMainThreadException

How to fix it? Or any workaround to interept http errors in webview? Thanks

A:

android.os.NetworkOnMainThreadException occurs whenever you try to make long running tasks/process on Main UI Thread directly.
To resolve this issue, cover your webservice call inside AsyncTask. FYI, AsyncTask in android known as Painless Threading which means developer don't need to bother about Thread management. So Go and implement web API call or any long running tasks using AsyncTask, there are plenty of examples available on the web.
Update:

I only want to load webview if http response code is 200.

=> Based on your requirement, I would say include your code inside doInBackground() method and return status code value, Which you can check inside onPostExecute(). Now here you are getting status code value 200/201 then you can load WebView.

A:

class HTTPRequest extends AsyncTask<int, Void, void> {

    protected int doInBackground() {
        try {
            HttpGet httpRequest = new HttpGet( "http://example.com");
            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = httpclient.execute(httpRequest);
            int code = response.getStatusLine().getStatusCode();
            return code;
        } catch (Exception e) {
           e.printstacktrace();

        }
    }

    protected void onPostExecute(int code) {
        // TODO: check this.exception 
        // retrieve your 'code' here
    }
 }

