Android NetworkOnMainThreadException [duplicate]

2020-05-10 10:44发布

问题:

I got an android.os.NetworkOnMainThreadException when I try to retreive JSON data from my PC-host, here is my code

public JSONObject getJSONObject(String url)
{
    Log.v("", "enter");
    DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
    Log.v("", "httpclient");
    HttpPost httppost = new HttpPost(url);
    Log.v("", "httppost");
    httppost.setHeader("Content-type", "application/json");
    Log.v("", "setHeader");
    InputStream inputStream = null;
    HttpResponse response;
    try
    {
            response = httpclient.execute(httppost);
            Log.v("", "response");
            HttpEntity entity = response.getEntity();
            Log.v("", "entity");
            inputStream = entity.getContent();
            Log.v("", "inputStream");
            Log.v("", buildJSONString( inputStream ));
            return new JSONObject( buildJSONString( inputStream ) );
    }
}

my call from activity

JSONObject jObject = (new JSONParser(this))
                .getJSONObject("http://192.168.0.81:8080/content/test.json");

and my logcat

09-12 12:32:05.878: V/(11103): enter
09-12 12:32:05.878: V/(11103): httpclient
09-12 12:32:05.878: V/(11103): httppost
09-12 12:32:05.878: V/(11103): setHeader
09-12 12:32:05.878: W/System.err(11103): android.os.NetworkOnMainThreadException
09-12 12:32:05.888: W/System.err(11103):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1108)
09-12 12:32:05.888: W/System.err(11103):    at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
09-12 12:32:05.888: W/System.err(11103):    at libcore.io.IoBridge.connectErrno(IoBridge.java:133)
09-12 12:32:05.888: W/System.err(11103):    at libcore.io.IoBridge.connect(IoBridge.java:118)
09-12 12:32:05.888: W/System.err(11103):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
09-12 12:32:05.888: W/System.err(11103):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
09-12 12:32:05.888: W/System.err(11103):    at java.net.Socket.connect(Socket.java:849)
09-12 12:32:05.888: W/System.err(11103):    at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
09-12 12:32:05.888: W/System.err(11103):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:154)
09-12 12:32:05.888: W/System.err(11103):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
09-12 12:32:05.888: W/System.err(11103):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
09-12 12:32:05.888: W/System.err(11103):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
09-12 12:32:05.888: W/System.err(11103):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:580)
09-12 12:32:05.888: W/System.err(11103):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:512)
09-12 12:32:05.888: W/System.err(11103):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:490)
09-12 12:32:05.888: W/System.err(11103):    at com.dwaik.jsonparser.JSONParser.getJSONObject(JSONParser.java:72)

it states that my exception is at response = httpclient.execute(httppost);
I got internet permission , access to server actually I can download files from it within same app.
Any idea?

回答1:

You are not allowed to do network operations with the Main (UI) thread.

There are several ways of using background threads. I would recommend using AsyncTask since it has a nice structure which is easy to understand.

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

Here is an SO example also: AsyncTask Android example

Should be a lot more available on Google.



回答2:

Android NetworkOnMainThreadException

Because you are performing n/w operations on main Ui thread

Either Use AsyncTask or Thread

AsyncTask: Docs

class myAsync extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub

                // Keep in mind You Can't Update UI Part here

              JSONObject jObject = (new JSONParser(this))
                .getJSONObject("http://192.168.0.81:8080/content/test.json");
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
                // Handle/Update UI Part
        }
    }

Call it like

new myAsync().execute();