HTTP Response in Android

This question already has an answer here:

  • How do I fix android.os.NetworkOnMainThreadException? 49 answers

  • 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.


    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
        }
     }
    

    You are getting this Exception because you are carrying out a heavy Computation ie Acessing Network in your case on UI Thread.

    You should never do this .

    Rather you can move this code to background Java Thread : Try :

    private void doNetworkCompuation()
    {
     new Thread(new Runnable() {
    
                @Override
                public void run() {
    
    HttpGet httpRequest = new HttpGet( "http://example.com");
    
    HttpClient httpclient = new DefaultHttpClient();
    
    HttpResponse response = httpclient.execute(httpRequest);
    
    int code = response.getStatusLine().getStatusCode();
    
    }).start();
    }
    
    链接地址: http://www.djcxy.com/p/29540.html

    上一篇: 如何解决android.os.NetworkOnMainThreadException?

    下一篇: Android中的HTTP响应