If you try to send the json as a parameter in url via Spring’s RestTemplate
, you will encounter the following error:
HttpClientErrorException$BadRequest: 400 : [{"Message":"Wrong format. See specification description; Unexpected character ('%' (code 37)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')\n at [Source: (String)\... (541 bytes)]
In order to solve this problem, you need to:
- Encode the URL yourself
- Disable url encoding at the
RestTemplate
level.
Let’s do that:
private String encodeUrl(String apiBaseUrl) throws Exception {
URIBuilder b = new URIBuilder(apiBaseUrl);
b.addParameter("jsonArg", "{\"field1\":\"value1\"}");
b.addParameter("simpleArg", "value2");
return b.build().toString();
}
RestTemplate restTemplate = new RestTemplate();
...
DefaultUriBuilderFactory defaultUriBuilderFactory = new DefaultUriBuilderFactory();
defaultUriBuilderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.NONE);
restTemplate.setUriTemplateHandler(defaultUriBuilderFactory);
String url = encodeUrl("http://localhost:8080");
String response = restTemplate.getForObject(url, String.class);
Many thanks to Chris Liu for showing how to disable url encoding in RestTemplate: http://www.chrispad.com/2019/04/disable-encoding-url-using-resttemplate.html.
Telegram channel
If you still have any questions, feel free to ask me in the comments under this article or write me at promark33@gmail.com.
If I saved your day, you can support me 🤝