Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use query parameter represented as JSON with Spring RestTemplate?

I need to make a request to an HTTP endpoint having a query parameter represented as JSON using Spring RestTemplate.

restTemplate.getForObject(
    apiRoot + "/path" + "?object={myObject}",
    Response.class,
    new MyObject())

Here I need MyObject to be converted to JSON (and URL-encoded obviously). But RestTemplate just converts it to String with toString call instead. MyObject is convertable to JSON by Jackson. UriComponentsBuilder behaves the same way:

UriComponentsBuilder.fromHttpUrl(apiRoot)
    .path("/path")
    .queryParam("object", new MyObject()))
    .queryParam("access_token", accessToken)
    .toUri()

Is there a way to avoid calling ObjectMapper.writeValueAsString by hands?

Update: to clarify, in the result I need to have ?object={"key":42} in my URI (or in URL-encodeded form ?object=%7B%22key%22%3A42%7D) given MyObject has one property key with value equal to 42.

like image 835
raindev Avatar asked Oct 31 '25 15:10

raindev


1 Answers

What is wrong with using writeValueAsString ? Can You explain?

The only solution that comes to my mind looks like (I don't think if there is a way for Jackson to know that this object should be serialized in that moment):

@Autowired
ObjectMapper objectMapper;

@Override
public void run(String... strings) throws Exception {

    String urlBase = "http://localhost:8080/path";

    RestTemplate restTemplate = new RestTemplate();

    String url;
    MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
    params.set("object", objectMapper.writeValueAsString(new MyObject()));

    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(urlBase).queryParams(params);
    url = builder.build().toUri().toString();

    LOGGER.info("Composed before decode: " + url);

    //restTemplate.getForObject(url, Void.class);

    url = URLDecoder.decode(url, "UTF-8");

    LOGGER.info("Composed after decode: " + url);
}

Output:

2016-04-05 16:06:46.811  INFO 6728 --- [main] com.patrykwoj.StackOverfloApplication    : Composed before decode: http://localhost:8080/path?object=%7B%22key%22:43%7D
2016-04-05 16:06:46.941  INFO 6728 --- [main] com.patrykwoj.StackOverfloApplication    : Composed after decode: http://localhost:8080/path?object={"key":43}

Edit:

I forgot to mention, that sending JSON object as request parameter is generally not a good idea. For example, You will probably face problem with curly brackets inside JSON.

like image 170
patrykos91 Avatar answered Nov 03 '25 05:11

patrykos91



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!