Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST with Jersey client using APPLICATION_FORM_URLENCODED mediatype

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);
like image 659
jmoreira Avatar asked Jan 15 '23 04:01

jmoreira


2 Answers

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.

like image 133
Perception Avatar answered Jan 25 '23 16:01

Perception


You can do it but first you have to create an Entity (javax.ws.rs.client.Entity) based on a Form (javax.ws.rs.core.Form) that maps the parameters expected by the service:

Form input = new Form();
input.param("first_parameter", "value");
input.param("second_parameter", "value");
Entity<Form> entity = Entity.entity(input, MediaType.APPLICATION_FORM_URLENCODED);

ClientResponse response = client.resource(url).type(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.APPLICATION_JSON).post(entity);
like image 29
Sergio Gabari Avatar answered Jan 25 '23 18:01

Sergio Gabari