java - Java/Android 的 HTTP POST 数组参数

标签 java android http

在 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/

相关文章:

java - 从 java 运行自动热键 (ahk) 脚本

java - 调用从 main 方法扩展另一个类的类

android - Activity 家长

mysql - Angular 7 : Cannot add or update a child row: a foreign key constraint fails

android - 连接超时时数据是否已经发送到服务器

java - 无法连接到 sqlite 数据库 - _syscall() 中出现内部错误

java - Guava 的 FluentIterable 线程安全

android - 如何在 fragment 内实现带有标签条的 Viewpager?

java - 将 android 的推送通知与 localytics 集成

asp.net - 是什么导致 IIS 接收到 HTTP 动词 "2GET"