【问题标题】:How to post array parameters with HttpComponents如何使用 HttpComponents 发布数组参数
【发布时间】:2011-09-05 14:08:40
【问题描述】:

我想用 Apache http-components (4.1.2) 执行这个命令

 curl  --data "strings[]=testOne&string-keys[]=test.one&strings[]=testTwo&string-keys[]=test.two&project=Test" https://api.foo.com/1/string/input-bulk

目标api需要stringsstring-keys参数作为array,这意味着重复strings[]以及每个参数的 string-keys[]

此 curl 命令可以正常工作,但使用 Http 组件,而我得到的参数完全相同。

也许我做错了什么。

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add( new BasicNameValuePair( "project", PROJECT_NAME ) );

    for ( Entry entry : newEntries )
    {
        params.add( new BasicNameValuePair( "string-keys[]", entry.getKey() ) );
        params.add( new BasicNameValuePair( "strings[]", entry.getValue() ) );
        params.add( new BasicNameValuePair( "context[]", "" ) );
    }

    URI uri = URIUtils.createURI( "https", "api.foo.com", -1, "/1/string/input-bulk", null, null );

    UrlEncodedFormEntity paramEntity = new UrlEncodedFormEntity( params );
    logger.info( "POST params : {}", EntityUtils.toString( paramEntity ) );
    HttpPost httpRequest = new HttpPost( uri );
    httpRequest.setEntity( paramEntity );

    HttpResponse response = new DefaultHttpClient().execute( httpRequest );

POST 参数如下所示:

POST params : project=Test&string-keys%5B%5D=test.one&strings%5B%5D=TestOne&string-keys%5B%5D=test.two&strings%5B%5D=TestTwo

如果我将它们放在 curl 中的 --data 后面,它可以工作,但不适用于 HttpCoponents。 谁能解释一下为什么?

提前致谢

【问题讨论】:

    标签: java http apache-httpclient-4.x apache-httpcomponents


    【解决方案1】:

    尝试在您的 httpRequest 中添加标头“application/x-www-form-urlencoded”

    
        httpRequest.addHeader("content-type", "application/x-www-form-urlencoded");
        HttpResponse response = new DefaultHttpClient().execute( httpRequest );
    

    希望这会奏效

    【讨论】:

    • 你试过用 StringEntity 代替 UrlEncodedFormEntity 吗?
    • 好的,所以使用 StringEntity 不会改变任何东西,看来我的问题与编码无关。我更新了我的问题。
    • 让我们再尝试一件事。我在几个地方读到同名的输入表单应该组合在一起并用逗号分隔。也许 curl 会为您进行分组,而 Android 不会。因此对于具有 value1 和 value2 的 strings[],​​您应该在键值对中包含 strings[]=value1,value2。
    • 谢谢,但我决定切换到 httpclient 3.x,一切都像魅力一样工作(+1 为您的帮助;))
    • @tbruyelle 什么有效?您正在使用字符串实体?我有类似的问题...我想发送 List ...不知道该怎么做。我正在拨打网络服务电话。 cxf 中有 WebClient 直接获取列表,但我被 httpclient 4.x 卡住了
    猜你喜欢
    • 1970-01-01
    • 2016-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    • 2019-04-29
    • 1970-01-01
    相关资源
    最近更新 更多