-1

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

httpclient.execute(httppost);

我真的不知道为什么。PS 我在 manifest.xml 文件中授予了 INTERNET 权限。这是我的代码,看起来可以在除我之外的任何其他人身上使用。

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 问题)。

谢谢你们。

这是 LogCat:

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

任何想法?

4

4 回答 4

1

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

于 2013-11-05T15:42:46.927 回答
1

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

于 2014-08-27T17:29:28.537 回答
1

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

于 2017-02-23T08:59:32.107 回答
0

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

于 2013-11-05T15:34:00.800 回答