How to post array parameters with HttpComponents

假如想象 提交于 2019-12-08 04:32:20

问题


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:


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



来源:https://stackoverflow.com/questions/7309237/how-to-post-array-parameters-with-httpcomponents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!