从Android发送数据

时间:2011-06-02 07:32:58

标签: java php android

我想将数据从Android设备发送到PHP。我试过,但我错了,我不知道。我该如何纠正?

这是我所做的Android代码。

public class php_connect extends Activity {
    InputStream is;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main1);
        JSONObject json = new JSONObject();
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://10.0.2.2/food/food.php");
            json.put("id",1);
            json.put("name","john");
            Log.i("jason Object", json.toString());
            httppost.setHeader("json", json.toString());

            StringEntity se = new StringEntity(json.toString());
            se.setContentEncoding("UTF-8");
            se.setContentType("application/json");
            httppost.setEntity(se);
            HttpResponse response = httpclient.execute(httppost);
            int statusCode = response.getStatusLine().getStatusCode();
            Toast.makeText(getApplicationContext(),String.valueOf(statusCode), Toast.LENGTH_SHORT).show();
            is = se.getContent();
            Log.e("log_tag", "connection success ");
            Toast.makeText(getApplicationContext(), "Successfully Connected", Toast.LENGTH_SHORT).show();
        }
        catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
            Toast.makeText(getApplicationContext(), "Fail to Connect", Toast.LENGTH_SHORT).show();
        }
    }
}

我得到响应为200并成功连接但无法在PHP中查看数据。

我的PHP代码是:

<?php
    $data = file_get_contents('php://input');
    $json = json_decode($data,true);
    var_dump($json);
    $id=$json['id'];
    echo $id;
?>

我总是得到空结果。

1 个答案:

答案 0 :(得分:1)

来自PHP manual

  

在POST请求的情况下,它更喜欢$ HTTP_RAW_POST_DATA,因为它不依赖于特殊的php.ini指令。此外,对于默认情况下未填充$ HTTP_RAW_POST_DATA的情况,它可能是激活always_populate_raw_post_data的内存密集型替代方案。 php://输入不适用于enctype =“multipart / form-data”

我认为将JSON编码为表单参数会更容易,并使用普通的PHP $ _POST函数来读取它:

List parameters = new ArrayList();
parameters.add(new BasicNameValuePair("jsonParam", json.toString())
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters)
httppost.setContentType("multipart/form-data");
httppost.setEntity(formEntity);   

在PHP方面你可以做到

Got <?php echo $_POST["jsonParam"]; ?>!<br />

注意:我没有测试过上面的代码。