HTTP POST Array Params for Java/Android
When building a HTTP POST Query in PHP I can use a simple method called: http_build_query which will return the following based on the array passed to function:
Simple array:
Array
(
[0] => foo
[1] => bar
[2] => baz
[3] => boom
[cow] => milk
[php] => hypertext processor
)
Returns:
flags_0=foo&flags_1=bar&flags_2=baz&flags_3=boom&cow=milk&php=hypertext+processor
A Bit more complex array:
Array
(
[user] => Array
(
[name] => Bob Smith
[age] => 47
[sex] => M
[dob] => 5/12/1956
)
[past开发者_如何学Cimes] => 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
)
Returns:
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
What I'm asking is, is there any way to create the latter entity format in Java/Android? I've tried the following without any 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));
Hopefully someone know how to achieve this :) Kind regards, Morten
EDIT:
Basically what i need is to to product 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 application/x-www-form-urlencoded format ;)
BTW. Thanks alot for answering sudocode, really appriciate it!
I've got it. Here's the sample code:
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);
A bit nasty, but it's working. You may want to get it a bit more generic - this is for 1-element array only.
I think your code is correct, but your expectation of what output it should produce is incorrect. I don't think you should expect your parameter names to be surrounded in square brackets (urlencoded: %5B and %5D).
If you need that, then you will need to add the brackets to your Java code, e.g.
nameValuePairs.add(new BasicNameValuePair("[firstname]", "admin"));
精彩评论