Send JSON in URL parameters


What's inside this article ⌄
  • RestTemplate JSON URL parameter
  • How to send JSON in URL spring
  • Spring RestTemplate JSON parameters
  • Pass JSON parameter 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)]

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();
}

And respectively:

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);