HttpURLConnection throws an exception

Here is my connection code 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();

it throws android.os.NetworkOnMainThreadException

Please, help.

+5
source share
2 answers

android.os.NetworkOnMainThreadException occurs because you are making a network call in your main UI thread. Use asynctask instead.

Asynctask documentation. http://developer.android.com/reference/android/os/AsyncTask.html .

Call AsyncTask in your user interface 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
 }
}

: AsyncTask Thread Handler . AsyncTasks ( ). , API, java.util.concurrent pacakge, , ThreadPoolExecutor FutureTask.

asynctask robospice. https://github.com/octo-online/robospice.

robospice.

1. ( AndroidService) (: REST Spring Android).

2. ! POJO, POJO .

3. POJO, , , .

4. ( Json , Gson, Xml, , , ORM Lite).

5.notify ( ) ,

6.no , Android-, Android AsyncTasks .

7. , .

+25

NetworkOnMainThreadException. , , .

sendfeedback asynctask, . - , , . , . , asynctask.

http://android-developers.blogspot.in/2009/05/painless-threading.html

+4

All Articles