开发者

How to post array parameters with HttpComponents

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=TestTw开发者_如何转开发o

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

Thanks in advance


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜