【问题标题】:android json post to phpandroid json 发布到 php
【发布时间】:2011-08-28 15:57:14
【问题描述】:

我已经完成了原始的休息获取和发布,也可以在名称值对中发布,但无论我遵循哪个教程,我都无法完成 json 发布...

Android 应用程序:

ArrayList<String> stringData = new ArrayList<String>();
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost postMethod = new HttpPost("http://192.168.1.10/people.php");     

JSONObject holder = new JSONObject();
holder.put("name", "Foo");    
holder.put("occupation", "Bar");

StringEntity se = new StringEntity(holder.toString());
postMethod.setEntity(se);
postMethod.setHeader("Accept", "application/json");
postMethod.setHeader("Content-type", "application/json");

ResponseHandler <String> resonseHandler = new BasicResponseHandler();
String response=httpClient.execute(postMethod,resonseHandler); 
stringData.add(response);

return stringData;

PHP 文件:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

 var_dump($_POST);
}

var_dump 只给出一个空数组,而 $_POST["name"] 给出未定义的索引...任何帮助都会很好

【问题讨论】:

    标签: php android json


    【解决方案1】:

    您是否尝试将holder.toString()BasicNameValuePair 类一起发送?

    喜欢

    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("myjson", holder.toString());
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
    

    然后就在你的 php 中你得到它就像

    $jsonstring = $_REQUEST['myjson'];
    

    【讨论】:

    • 也许您需要在您的 php 代码中对其进行解码。如果需要解码,请使用$jsonstring = urldecode($_REQUEST['myjson'];
    • 这个答案对我有用:)
    【解决方案2】:

    另外两种读取 POST 数据的方法:

    1. php://input 读取
    2. 使用变量 $HTTP_POST_RAW_DATA。

    http://www.php.net/manual/en/reserved.variables.httprawpostdata.php

    【讨论】:

      【解决方案3】:

      我认为问题可能出在您使用的网址上。

      发布到 10.0.2.2,而不是您在 http 帖子中指定的那个。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-02
        • 2012-08-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多