HttpClient.execute(HttpPost) on Android 4.2 error

前端 未结 2 1804
生来不讨喜
生来不讨喜 2020-12-10 00:02

I am following this website http://givemepass.blogspot.hk/2011/12/http-server.html to try to use the android application connect the PHP server to get message.

GetS

相关标签:
2条回答
  • 2020-12-10 00:22

    You are running network related operation on the ui thread. You will get NetworkOnMainThreadException post honeycomb.

    Use a Thread or Asynctask

    Invoke asynctask

       new TheTask().execute("http://192.168.1.88/androidtesting.php");
    

    AsyncTask

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

    class TheTask extends AsyncTask<String,String,String>
        {
    
    @Override
    protected String onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        // update textview here
        textView.setText("Server message is "+result);
    }
    
    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
    }
    
    @Override
    protected String doInBackground(String... params) {
         try
            {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost method = new HttpPost(params[0]);
                HttpResponse response = httpclient.execute(method);
                HttpEntity entity = response.getEntity();
                if(entity != null){
                    return EntityUtils.toString(entity);
                }
                else{
                    return "No string.";
                }
             }
             catch(Exception e){
                 return "Network problem";
             }
    
    }
    }
    

    Update HttpClient is deprecated in api 23. Use HttpUrlConnection.

    http://developer.android.com/reference/java/net/HttpURLConnection.html

    0 讨论(0)
  • 2020-12-10 00:32

    You need to run long running tasks, like network, calls on a separate Thread as Sotirios Delimanolis said. AsyncTask is probably the way to go.

    0 讨论(0)
提交回复
热议问题