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

前端 未结 1 345
情歌与酒
情歌与酒 2021-01-22 17:11

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

res         


        
1条回答
  •  余生分开走
    2021-01-22 17:38

    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 params = new LinkedMultiValueMap();
        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.

    0 讨论(0)
提交回复
热议问题