Java Android 4.2 上的 HttpClient.execute(HttpPost) 错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19162272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 14:37:46  来源:igfitidea点击:

HttpClient.execute(HttpPost) on Android 4.2 error

javaandroid

提问by Confucius

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

我正在关注这个网站http://givemepass.blogspot.hk/2011/12/http-server.html尝试使用 android 应用程序连接 PHP 服务器来获取消息。

GetServerMessage.java

获取服务器消息.java

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class GetServerMessage {

    public String stringQuery(String url){
        try
        {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost method = new HttpPost(url);
            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";
         }
    }
}

GetPhpServerMessageDemoActivity.java

GetPhpServerMessageDemoActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class GetPhpServerMessageDemoActivity extends Activity {
    /** Called when the activity is first created. */
    private TextView textView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        textView = (TextView)findViewById(R.id.text_view);
        GetServerMessage message = new GetServerMessage();
        String msg = message.stringQuery("http://192.168.1.88/androidtesting.php");
        textView.setText("Server message is "+msg);
    }

}

I tried to download the Android Application Project from that site http://uploadingit.com/file/d4632ekfpwjiupyn/GetPhpServerMessageDemo2.zipand run on my phone, it's work. But when I start a new project (Minimuim Requied SDK: API8, Target SDK: API17, Compile with: API17) and copy these two java codes. I've added the permission android.permission.INTERNET, so I don't know where is the problem, I only know that when run HttpResponse response = httpclient.execute(method);there is a error and returned String "Network problem".

我试图从该站点http://uploadingit.com/file/d4632ekfpwjiupyn/GetPhpServerMessageDemo2.zip下载 Android 应用程序项目并在我的手机上运行,​​它的工作。但是当我开始一个新项目(Minimuim Requied SDK: API8, Target SDK: API17, Compile with: API17)并复制这两个java代码时。我已经添加了权限android.permission.INTERNET,所以我不知道问题出在哪里,我只知道运行时HttpResponse response = httpclient.execute(method);出现错误并返回字符串“网络问题”。

采纳答案by Raghunandan

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

您正在 ui 线程上运行网络相关操作。你会得到NetworkOnMainThreadException后蜂窝。

Use a Threador Asynctask

使用一个ThreadAsynctask

Invoke asynctask

调用异步任务

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

AsyncTask

异步任务

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

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.

更新 HttpClient 在 api 23 中已弃用。使用HttpUrlConnection.

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

回答by Emmanuel

You need to run long running tasks, like network, calls on a separate Threadas Sotirios Delimanolis said. AsyncTaskis probably the way to go.

你需要运行长时间运行的任务,比如网络,Thread就像 Sotirios Delimanolis 所说的那样,单独调用。AsyncTask可能是要走的路。