Mapping POJOs to application/x-www-form-urlencoded with custom form keys
Asked Answered
C

0

6

I'm using RoboSpice with Spring Android to perform REST api calls. Data need to be sent with the Content-Type set to application/x-www-form-urlencoded.

Let's say I have a Pojo class like this:

public class Pojo {
  private String pojoAttribute;

  // getter + setter
}

Here is my request class:

public class PojoRequest extends AbstractApiRequest<PojoResult> {

    private Pojo pojo;

    public PojoRequest(Pojo pojo) {
        super(PojoResult.class);
        this.pojo = pojo;
    }

    @Override
    public PojoResult loadDataFromNetwork() throws Exception {

        HttpEntity<Pojo> requestEntity = new HttpEntity<Pojo>(pojo, getDefaultHeaders());
        String url = buildUrlForPath("mypath");

        RestTemplate restTemplate = getRestTemplate();
        restTemplate.getMessageConverters().add(new FormHttpMessageConverter());

        return restTemplate.postForObject(url, requestEntity, PojoResult.class);
    }
}

So, suppose I need to send this body:
pojo_attribute=foo

Now my code does not work because FormHttpMessageConverter does not handle POJOs.

What I would like to be able to do is something like this:

public class Pojo {
  @FormProperty("pojo_attribute")
  private String pojoAttribute;

  // getter + setter
}

With a magic HttpMessageConverter that converts my POJO into key=value format taking care of converting the pojoAttribute to pojo_attribute by inspecting the @FormProperty (does not exist) annotation the same way Jackson does with @JsonProperty.

My questions are:
- is it possible to do this with existing classes/annotations?
- is there another way to do something similar?
- would it be overkill if I create my own HttpMessageConverter and set of annotations to do just that?

Carr answered 25/7, 2014 at 2:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.