HTTP POST Array Params for Java / Android

When creating an HTTP POST request in PHP, I can use a simple method: http_build_query, which will return the following based on the array passed to the function:

Simple array:

Array
(
    [0] => foo
    [1] => bar
    [2] => baz
    [3] => boom
    [cow] => milk
    [php] => hypertext processor
)

Return:

flags_0=foo&flags_1=bar&flags_2=baz&flags_3=boom&cow=milk&php=hypertext+processor

Bit is a more complex array:

Array
(
[user] => Array
    (
        [name] => Bob Smith
        [age] => 47
        [sex] => M
        [dob] => 5/12/1956
    )

[pastimes] => Array
    (
        [0] => golf
        [1] => opera
        [2] => poker
        [3] => rap
    )

[children] => Array
    (
        [bobby] => Array
            (
                [age] => 12
                [sex] => M
            )

        [sally] => Array
            (
                [age] => 8
                [sex] => F
            )

    )

[0] => CEO
)

Return:

user%5Bname%5D=Bob+Smith&user%5Bage%5D=47&user%5Bsex%5D=M&user%5Bdob%5D=5%2F12%2F1956&pastimes%5B0%5D=golf&pastimes%5B1%5D=opera&pastimes%5B2%5D=poker&pastimes%5B3%5D=rap&children%5Bbobby%5D%5Bage%5D=12&children%5Bbobby%5D%5Bsex%5D=M&children%5Bsally%5D%5Bage%5D=8&children%5Bsally%5D%5Bsex%5D=F&flags_0=CEO

I ask, is there a way to create the latest entity format in Java / Android? I tried the following with no luck:

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("user", null));
nameValuePairs.add(new BasicNameValuePair("firstname", "admin"));
nameValuePairs.add(new BasicNameValuePair("lastname", "admin"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

Hope someone knows how to achieve this :) Regards, Morten

EDIT:

Basically, I need to write the Java equivalent of this PHP:

$params = array('user' => array(
    'firstname' => 'Bob Smith',
    'lastname' => 'Johnson'
));

And this is the same request in JSON format:

{"user":{"firstname":"Bob Smith","lastname":"Johnson"}}

I just need the Java equivalent in the format application / x-www-form-urlencoded;)

BTW. Thanks so much for responding to sudocode, really appriciate it!

+3
source share
2 answers

. :

        String data = EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
        data = "&" + data.replaceAll("%5B0%5D", "[0]");
        StringEntity se = new StringEntity(data, "UTF-8");
        se.setContentType("application/x-www-form-urlencoded");
        se.setContentEncoding("UTF-8");
        httppost.setEntity(se);

, . , - 1- .

+1

, , , , . , , (urlencoded:% 5B % 5D).

, Java-, .

nameValuePairs.add(new BasicNameValuePair("[firstname]", "admin"));
0

All Articles