如何使用HttpComponents发布数组参数

如何使用HttpComponents发布数组参数

本文介绍了如何使用HttpComponents发布数组参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to perform this command with 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需要字符串字符串键参数为 array ,表示为每个参数重复字符串[] 字符串键[]

The target api need strings and string-keys parameters as array, which mean repeating strings[] and string-keys[] for each parameter.

这个curl命令运行正常,但有Http组件,而我得到了完全相同的参数。

This curl command works fine but with Http-component, while I got exactly the same parameters.

也许我做错了什么。

    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参数看起来像:

The POST params looks like :

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。
有人可以解释一下原因吗?

If I put them behind --data in curl, it works, but not with HttpCoponents.Can someone explain me why?

提前致谢

推荐答案

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

Try adding the header "application/x-www-form-urlencoded" in your httpRequest


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

希望可以使用

这篇关于如何使用HttpComponents发布数组参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 17:10