如何使用jsonParser.makeHttpRequest将android对象列表发送到PHP脚本

时间:2018-01-15 14:17:54

标签: php android

我正在使用jsonParser.makeHttpRequest将变量从Android应用程序发送到PHP脚本。例如:

String url = "http://www.serwer17.com/script.php";
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userID", userID));
params.add(new BasicNameValuePair("userName", userName));
// getting JSON Object
JSONObject json = jsonParser.makeHttpRequest(url,"POST", params);

在我的Android应用程序中,我有课程:

class User
{
   int userAge;
   String userName;
   String userAddress;
}

我需要立即向php脚本发送三个变量:

   List<User> users
   int intValue
   String stringValue

如何将这些变量发送到PHP脚本? 我可以像以前一样使用jsonParser.makeHttpRequest吗?

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

为了从问题发送三个参数到PHP脚本。 Andriod App方面:

JSONArray jsonArray = new JSONArray();
for(int i=0; i<users.size(); i++)
{
    User userX = users.get(i);
    JSONObject jsonX= new JSONObject();
    try {
            jsonX.put("userAge", Integer.toString(userX.userAge));
            jsonX.put("userName", userX.userName);
            jsonX.put("userAddress", userX.userAddress);

            jsonArray.put(jsonX);

        } catch (JSONException e) {
            e.printStackTrace();
        }
}

JSONObject jsonObject= new JSONObject();
try {
        jsonObject.put("intValue", Integer.toString(intValue));
        jsonObject.put("jsonArrayX", jsonArray);
        jsonObject.put("stringValue", stringValue);
    } catch (JSONException e) {
        e.printStackTrace();
    }

JSONParser jsonParser = new JSONParser();

String url = "http://www.serwerx/example.php";

// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("post", jsonObject.toString()));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url, "POST", params);

PHP脚本站点:

if(isset($_POST['post']))
{
    $postX = htmlspecialchars_decode(htmlentities($_POST['post']));

    $post_x = json_decode($postX, true);


    //to get received string value or int value
    $intValue = $post_x['intValue'];
    $stringValue = $post_x['stringValue'];

    //to display received json array 
    $jsonArray_size = count($post_x['jsonArrayX']);
    for($i=0; $i<$jsonArray_size; $i++)
    {
        echo $post_x['jsonArrayX'][$i]['userAge'];
        echo $post_x['jsonArrayX'][$i]['userName'];
        echo $post_x['jsonArrayX'][$i]['userAddress'];
    }

}
相关问题