Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST using JAX-RS 2.0 Client API

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!

like image 212
user2824073 Avatar asked May 22 '14 13:05

user2824073


People also ask

What is JAX-RS client API?

JAX-RS provides a client API for accessing REST resources from other Java applications. The following topics are addressed here: Overview of the Client API. Using the Client API in the JAX-RS Example Applications. Advanced Features of the Client API.


1 Answers

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);
like image 144
pWoz Avatar answered Oct 08 '22 22:10

pWoz