How to post array parameters with HttpComponents

2019-05-31 10:11发布

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

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

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

Maybe I'm doing something wrong.

    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 );

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

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

Thanks in advance

1条回答
小情绪 Triste *
2楼-- · 2019-05-31 10:39

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 );

Hopefully that will work

查看更多
登录 后发表回答