在 PHP 中构建 HTTP POST 查询时,我可以使用一个名为 http_build_query 的简单方法,它将根据传递给函数的数组返回以下内容:
简单数组:
Array
(
[0] => foo
[1] => bar
[2] => baz
[3] => boom
[cow] => milk
[php] => hypertext processor
)
返回:
flags_0=foo&flags_1=bar&flags_2=baz&flags_3=boom&cow=milk&php=hypertext+processor
有点复杂的数组:
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
)
返回:
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
我想问的是,有没有办法在 Java/Android 中创建后一种实体格式?我已经尝试了以下但没有任何运气:
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));
希望有人知道如何实现这一点:) 亲切的问候, 莫腾
编辑:
基本上我需要的是生成与此 PHP 等效的 Java:
$params = array('user' => array(
'firstname' => 'Bob Smith',
'lastname' => 'Johnson'
));
这是 JSON 格式的相同请求:
{"user":{"firstname":"Bob Smith","lastname":"Johnson"}}
我只需要 application/x-www-form-urlencoded 格式的 Java 等价物 ;)
顺便说一句。非常感谢您回答 sudocode,非常感谢!
最佳答案
我知道了。这是示例代码:
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 元素数组。
关于java - Java/Android 的 HTTP POST 数组参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5938113/