In a Java method, I'd like to use a Jersey client object to do a POST operation on a RESTful web service (also written using Jersey) but am not sure how to use the client to send the values that will be used as FormParam's on the server. I'm able to send query params just fine.
You can use it to add form data and send it to the server: WebTarget webTarget = client. target("http://www.example.com/some/resource"); MultivaluedMap<String, String> formData = new MultivaluedHashMap<String, String>(); formData. add("key1", "value1"); formData.
Jersey is an open source framework for developing RESTFul Web Services. It also has great inbuilt client capabilities.
Jersey ClientBuilder. JAX-RS Client API is a designed to allow fluent programming model. To create jersey client follow these steps – Use ClientBuilder. newClient() static method.
Not done this yet myself, but a quick bit of Google-Fu reveals a tech tip on blogs.oracle.com with examples of exactly what you ask for.
Example taken from the blog post:
MultivaluedMap formData = new MultivaluedMapImpl(); formData.add("name1", "val1"); formData.add("name2", "val2"); ClientResponse response = webResource .type(MediaType.APPLICATION_FORM_URLENCODED_TYPE) .post(ClientResponse.class, formData);
That any help?
Starting from Jersey 2.x, the MultivaluedMapImpl
class is replaced by MultivaluedHashMap
. You can use it to add form data and send it to the server:
WebTarget webTarget = client.target("http://www.example.com/some/resource"); MultivaluedMap<String, String> formData = new MultivaluedHashMap<String, String>(); formData.add("key1", "value1"); formData.add("key2", "value2"); Response response = webTarget.request().post(Entity.form(formData));
Note that the form entity is sent in the format of "application/x-www-form-urlencoded"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With