Send JSON as parameter in url using RestTemplate

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:

  1. Encode the URL yourself
  2. 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");

RestTemplate restTemplate = new RestTemplate();
DefaultUriBuilderFactory defaultUriBuilderFactory = new 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:

Telegram channel

If you still have any questions, feel free to ask me in the comments under this article or write me at

If I saved your day, you can support me 🤝

Leave a Reply

Your email address will not be published. Required fields are marked *