POST using JAX-RS 2.0 Client API

user2824073 picture user2824073 · May 22, 2014 · Viewed 27.4k times · Source

I have a REST Service which exposes a POST service using Form Parameters:

@POST
@Path("/add")
@Produces("text/html")
public Response create(@FormParam("key")String key,
            @FormParam("value")String value)
{    
    service.addToList(key,value);    
    return Response.ok(RESPONSE_OK).build();     

} 

I need to find a way out to invoke this service using the JAX-RS client API. Unfortunately the only examples available on the net make use of an Entity class that is passed to your Web target resource:

StoreOrder order = new StoreOrder(...);
WebTarget myResource = client.target("http://example.com/webapi/write");
TrackingNumber trackingNumber = myResource.request(MediaType.APPLICATION_XML)
                                   .post(Entity.xml(order), TrackingNumber.class);

Any idea how I can invoke my service passing single parameters (maybe form parameters) ? Thanks!

Answer

pWoz picture pWoz · May 27, 2014

You should use: javax.ws.rs.client.Entity<T> combined with javax.ws.rs.core.Form. Here is a simple example:

Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:9998").path("resource");

Form form = new Form();
form.param("key", "foo");
form.param("value", "bar");

TrackingNumber requestResult =
target.request(MediaType.APPLICATION_JSON_TYPE)
    .post(Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED_TYPE),
        TrackingNumber.class);