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

半腔热情 提交于 2019-12-02 05:34:40

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/36423202/how-to-use-query-parameter-represented-as-json-with-spring-resttemplate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!