POST with Jersey client using APPLICATION_FORM_URLENCODED mediatype

jakarta-ee, java, jersey

Solution

JAX-RS providers are only required to provide mappings to `application/x-www-form-urlencoded` for `MultivaluedMap<String,String>`. And I'm pretty sure that out-of-the-box Jersey doesn't provide an additional mapper from `application/x-www-form-urlencoded` to regular POJOs. You could write your own client side provider, but depending on how often you need to do this it may be simpler to just map the POJO fields to the URL fields yourself.

Problem

I have to post a pojo to a server that only accepts parameters via form data (MediaType.APPLICATION_FORM_URLENCODED). I know jersey client can convert the object to xml, json and other types but trying to convert to APPLICATION_FORM_URLENCODED gives an exception showing that no body writer for the specified types is available. Is there a way to serialize the object to be an application_form_urlencoded MultivaluedMap, or i have to manually take attribute by attribute to form the resultant MultivaluedMap? Creating an Adapter to use jersey serialization doesn't seem to me to be the appropriate solution according to the problem context. Object to POST ``` @XmlRootElement public class POSTableObject { private int a; private String b; public int getA() { return a; } public void setA(int a) { this.a = a; } public String getB() { return b; } public void setB(String b) { this.b = b; } } ``` Post Action using Jersey client ``` ClientResponse response = client.resource(url).type(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, postableObject); ```

Original source