Android HttpClient : NetworkOnMainThreadException

▼魔方 西西 提交于 2019-11-26 10:00:28

问题


I have some code below:

protected void testConnection(String url) {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(url);
    ResponseHandler<String> responsehandler = new BasicResponseHandler();

    try {
        String connection = httpclient.execute(httpget, responsehandler);
        Toast.makeText(getBaseContext(), R.string.connection_succeed, Toast.LENGTH_SHORT).show();
        view_result.setText(connection);
    } catch(IOException e) {
        Toast.makeText(getBaseContext(), R.string.connection_failed, Toast.LENGTH_SHORT).show();
    }
    httpclient.getConnectionManager().shutdown();
}

and add a permission in Menifest:

<uses-permission android:name=\"android.permission.INTERNET\"/>

But it goes an exception: NetworkOnMainThreadException, How can i do?


回答1:


On ICS and later you cannot do network operations on the UI thread anymore. Instead you are forced to create a new thread and do your networking stuff there.

Possible tools are Android's AsyncTask and the normal Java Thread.

A good tutorial can be found here: Android Threads, Handlers and AsyncTask - Tutorial




回答2:


Starting from API 11, you can not manipulate network (time-consuming) operations on main thread. Use AsyncTask or Thread to perform such operations.




回答3:


You cant perform network operations in event thread, since android Api Level 11. Instead you should do network operation in another thread than event thread, and use Handler or Asynctask to do so.




回答4:


I you run your code in android 2.x and its lower version, i think this code will run perfectly. But if you run this in 3.x and it's upper version then you get an Exception. The problem is the you need to call the web service from your worker thread(AsyncTask<>) . You can not call the web service from the main thread.



来源:https://stackoverflow.com/questions/11736530/android-httpclient-networkonmainthreadexception

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