HttpURLConnection is throwing exception [duplicate]

情到浓时终转凉″ 提交于 2019-12-19 05:58:29

问题


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.


回答1:


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.

An alternative to asynctask in robospice. https://github.com/octo-online/robospice.

Some of the features of robospice.

1.executes asynchronously (in a background AndroidService) network requests (ex: REST requests using Spring Android).

2.is strongly typed ! You make your requests using POJOs and you get POJOs as request results.

3.enforce no constraints neither on POJOs used for requests nor on Activity classes you use in your projects.

4.caches results (in Json with both Jackson and Gson, or Xml, or flat text files, or binary files, even using ORM Lite).

5.notifies your activities (or any other context) of the result of the network request if and only if they are still alive

6.no memory leak at all, like Android Loaders, unlike Android AsyncTasks notifies your activities on their UI Thread.

7.uses a simple but robust exception handling model.




回答2:


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

You should call sendfeedback method on asynctask then only above code will work. As webserver is taking lot of time to response main thread becomes unresponsive. To avoid it you should call it on another thread. Hence asynctask is better.

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



来源:https://stackoverflow.com/questions/15496278/httpurlconnection-is-throwing-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!