Android 我的应用程序与 httpclient.execute(httpost) 一起崩溃


Android my app crash with the httpclient.execute(httpost)

我正在尝试将一些字符串发送到某个php文件并取回JSON变量。现在我被困在将我的字符串发送到我的 php 文件上,我尝试了许多教程中的许多组合,所有这些都

粉碎在:
httpclient.execute(httppost);

我真的不知道为什么。附言我在清单.xml文件中授予了互联网权限。这是我的代码,看起来可以在除我之外的任何其他人身上工作。

public void send()
{
    String  msg = "Some message text";

    if(msg.length()>0) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://localhost:8888/file.php");
        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("id", "01"));
            nameValuePairs.add(new BasicNameValuePair("message", msg));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            httpclient.execute(httppost);// THE APP CRASH HERE!!!
            Toast.makeText(getBaseContext(),"Sent",Toast.LENGTH_SHORT).show();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        Toast.makeText(getBaseContext(),"All fields are required", Toast.LENGTH_SHORT).show();
    }
}

目前我只想通过发送过程(接下来我将处理的 JSON 问题)。

谢谢大家。

这是日志猫:

288-299/system_process W/ActivityManager﹕ Force finishing activity com.example.testphppost/.MainActivity
11-05 17:37:56.011      288-299/system_process W/WindowManager﹕ Failure taking screenshot for (328x546) to layer 21010
11-05 17:37:56.294        37-89/? E/SurfaceFlinger﹕ ro.sf.lcd_density must be defined as a build property
11-05 17:37:56.542      288-302/system_process W/ActivityManager﹕ Activity pause timeout for ActivityRecord{40f0e4c8 u0 com.example.testphppost/.MainActivity}
11-05 17:37:56.762       37-184/? E/SurfaceFlinger﹕ ro.sf.lcd_density must be defined as a build property
11-05 17:37:58.141    2147-2147/? I/Process﹕ Sending signal. PID: 2147 SIG: 9
11-05 17:37:58.161      288-288/system_process I/ActivityManager﹕ Process com.example.testphppost (pid 2147) has died.
11-05 17:37:59.061      288-288/system_process W/InputMethodManagerService﹕ Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@40f27770 attribute=null, token = android.os.BinderProxy@40d32668

知道吗?

您可能正在主线程上发出请求。

很难说些什么,因为您没有提供有关异常的任何信息,但正如 Sherif elKhatib 所说,您需要异步发送请求。尝试查看AsyncTask。

看起来

您正在尝试在主线程上执行网络操作,您不能这样做。尝试 AsyncTask 或打开新线程。

android 的环回地址是 10.0.2.2,但您使用的是本地主机(表示 127.0.0.1)尝试更改它。并 http://www.androidhive.info/2012/01/android-json-parsing-tutorial/阅读本教程