HTTP POST request with android crashes [duplicate]

2019-08-30 05:47发布

问题:

This question already has an answer here:

  • How do I fix android.os.NetworkOnMainThreadException? 54 answers

I've the following java code:

try{
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://192.168.1.105/test.php");

    List<NameValuePair> teste = new ArrayList<NameValuePair>(1);
    teste.add(new BasicNameValuePair("test", "test"));
    httppost.setEntity(new UrlEncodedFormEntity(test));

    HttpResponse response = (HttpResponse) httpclient.execute(httppost);
} catch (IOException e) {
    e.printStackTrace();
}

Whenever I uncomment/comment the line HttpResponse response = (HttpResponse) httpclient.execute(httppost); the app crashes / doesn't crash, respectively. I have the internet permission on the manifest and I would like to obtain a json_encoded message from the server. I tried "everything" but still couldn't manage to put it to work.

Logs:

07-10 15:04:30.197: E/AndroidRuntime(19382): FATAL EXCEPTION: main 07-10 15:04:30.197: E/AndroidRuntime(19382): java.lang.IllegalStateException: Could not execute method of the activity 07-10 15:04:30.197: E/AndroidRuntime(19382): at android.view.View$1.onClick(View.java:3591) 07-10 15:04:30.197: E/AndroidRuntime(19382): at android.view.View.performClick(View.java:4084) 07-10 15:04:30.197: E/AndroidRuntime(19382): at android.view.View$PerformClick.run(View.java:16966) 07-10 15:04:30.197: E/AndroidRuntime(19382): at android.os.Handler.handleCallback(Handler.java:615) 07-10 15:04:30.197: E/AndroidRuntime(19382): at android.os.Handler.dispatchMessage(Handler.java:92) 07-10 15:04:30.197: E/AndroidRuntime(19382): at android.os.Looper.loop(Looper.java:137) 07-10 15:04:30.197: E/AndroidRuntime(19382): at android.app.ActivityThread.main(ActivityThread.java:4745) 07-10 15:04:30.197: E/AndroidRuntime(19382): at java.lang.reflect.Method.invokeNative(Native Method) 07-10 15:04:30.197: E/AndroidRuntime(19382): at java.lang.reflect.Method.invoke(Method.java:511) 07-10 15:04:30.197: E/AndroidRuntime(19382): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 07-10 15:04:30.197: E/AndroidRuntime(19382): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 07-10 15:04:30.197: E/AndroidRuntime(19382): at dalvik.system.NativeStart.main(Native Method) 07-10 15:04:30.197: E/AndroidRuntime(19382): Caused by: java.lang.reflect.InvocationTargetException 07-10 15:04:30.197: E/AndroidRuntime(19382): at java.lang.reflect.Method.invokeNative(Native Method) 07-10 15:04:30.197: E/AndroidRuntime(19382): at java.lang.reflect.Method.invoke(Method.java:511) 07-10 15:04:30.197: E/AndroidRuntime(19382): at android.view.View$1.onClick(View.java:3586) 07-10 15:04:30.197: E/AndroidRuntime(19382): ... 11 more 07-10 15:04:30.197: E/AndroidRuntime(19382): Caused by: android.os.NetworkOnMainThreadException 07-10 15:04:30.197: E/AndroidRuntime(19382): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117) 07-10 15:04:30.197: E/AndroidRuntime(19382): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84) 07-10 15:04:30.197: E/AndroidRuntime(19382): at libcore.io.IoBridge.connectErrno(IoBridge.java:127) 07-10 15:04:30.197: E/AndroidRuntime(19382): at libcore.io.IoBridge.connect(IoBridge.java:112) 07-10 15:04:30.197: E/AndroidRuntime(19382): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192) 07-10 15:04:30.197: E/AndroidRuntime(19382): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459) 07-10 15:04:30.197: E/AndroidRuntime(19382): at java.net.Socket.connect(Socket.java:842) 07-10 15:04:30.197: E/AndroidRuntime(19382): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119) 07-10 15:04:30.197: E/AndroidRuntime(19382): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144) 07-10 15:04:30.197: E/AndroidRuntime(19382): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 07-10 15:04:30.197: E/AndroidRuntime(19382): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 07-10 15:04:30.197: E/AndroidRuntime(19382): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 07-10 15:04:30.197: E/AndroidRuntime(19382): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 07-10 15:04:30.197: E/AndroidRuntime(19382): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 07-10 15:04:30.197: E/AndroidRuntime(19382): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 07-10 15:04:30.197: E/AndroidRuntime(19382): at com.diverse.just.LoginActivity.newAccount(LoginActivity.java:92) 07-10 15:04:30.197: E/AndroidRuntime(19382): ... 14 more

回答1:

You should put your code in the AsyncTask for background performance.

But for a better way of downloading Server data use a framework called AsyncHttpClient, you can find it here:

AsyncHttpClient



回答2:

You must execute the HTTP request part on another Thread.

For example:

        AsyncTask<String, Void, Void> db = null;
    try {
        db = new db_conn(this);
        db.execute("http://192.168.1.5/request.php").get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }

the .get() method waits for the AsyncTask to finish before the main thread continue its execution.

And the db class:

class db_conn extends AsyncTask<String, Void, Void> {    
    @Override
    protected Void doInBackground(String... params) {
        GetDataFromDB db = new GetDataFromDB();
        String url = params[0];
        System.out.println(url);
        jObject = db.makeHttpRequest(url, "GET", null);
        return null;
    }
....
.....

}


回答3:

Caused by: android.os.NetworkOnMainThreadException, you can't perform network request on main thread. Move it to background.