javarestjerseyjax-rsname-value

Sending Name Value Pair in POST using Jersey Client


How can i pass name value pairs as body to a POST ReST Service in Jersey. Something similar to the code below using Apache Commons PostMethod

    final PostMethod post = new PostMethod(url);
    post.setRequestBody(new NameValuePair[] {
            new NameValuePair("loginId", userId),
            new NameValuePair("logonPassword", password),
            new NameValuePair("signature", signature),
            new NameValuePair("timestamp", timestamp),
            new NameValuePair("sourceSiteId", sourceSiteId) });

I'm porting this call to my application. The current call uses apache commons PostMethod. In my application i used Jersey. So i want to use the jersey classes/features instead of apache.


Solution

  • There is a MultivaluedMap interface in JAX-RS with a 'MultivaluedMapImpl' in Jersey.

    Client client = Client.create();
    WebResource webResource = client.resource("http://site.com/resource");
    MultivaluedMap<String, String> map = new MultivaluedMapImpl();
    map.put("loginId", loginId);
    ...
    ClientResponse response = webResource.type("application/x-www-form-urlencoded")
                 .post(ClientResponse.class, map);
    

    Here is a more comprehensive example of how to use Jersey client API.