如何使用HttpComponents发布数组参数

时间:2011-09-05 14:08:41

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

我想用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需要字符串字符串键参数作为数组,这意味着重复字符串[] 每个参数都有 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 params看起来像:

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

如果我把它们放在卷曲中--data,它可以工作,但不能用HttpCoponents。 有人能解释我为什么吗?

提前致谢

1 个答案:

答案 0 :(得分:2)

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


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

希望这会起作用

相关问题