androidhttpurlconnection

HttpURLConnection is throwing exception


Here is my code to connect HTTP.

URL url = new URL("http://www.google.com");
              HttpURLConnection con = (HttpURLConnection) url.openConnection();
              con.setDoOutput(true);
              String responseMsg = con.getResponseMessage();
              int response = con.getResponseCode();

this is throwing android.os.NetworkOnMainThreadException

Please help.


Solution

  • android.os.NetworkOnMainThreadException occurs because you are making network call on your main UI Thread. Instead use a asynctask.

    Documentation of asynctask.http://developer.android.com/reference/android/os/AsyncTask.html.

    Call AsyncTask in your UI Thread.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        new MyDownloadTask().execute();
    
    }
    
    class MyDownloadTask extends AsyncTask<Void,Void,Void>
    {
    
    
        protected void onPreExecute() {
          //display progress dialog.
        
     }
        protected Long doInBackground(Void... params) {
              URL url = new URL("http://www.google.com");
              HttpURLConnection con = (HttpURLConnection) url.openConnection();
              con.setDoOutput(true);
              String responseMsg = con.getResponseMessage();
              int response = con.getResponseCode();
         return null;
     }
    
    
    
     protected void onPostExecute(VOid result) {
       // dismiss progress dialog and update ui
     }
    }
    

    Note : AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as Executor, ThreadPoolExecutor and FutureTask.

    Update 5thMarch 2024: AsyncTask is deprecated https://developer.android.com/reference/android/os/AsyncTask

    Use coroutines instead of the above. The above suggestion is outdated https://developer.android.com/kotlin/coroutines. Use context switching and appropriate dispatchers.

    Also switch to using Okhttp3 along with retrofit https://square.github.io/okhttp/