I have 2 string variables with sample input:
- content: "m/=a"
- sms: "TEST123 ~!@#$%^&*()_+{}:<>?"
I need to send these two variables as query params using GET method. Below is my code.
Creating rest template:
DefaultUriBuilderFactory defaultUriBuilderFactory = new DefaultUriBuilderFactory();
defaultUriBuilderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.NONE);
RestTemplate restTemplate = constructRestTemplate(cpConnectivity);
restTemplate.setUriTemplateHandler(defaultUriBuilderFactory);
Encode function:
return URLEncoder.encode(value, StandardCharsets.UTF_8);
Sending request:
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.newInstance()
.queryParam("content", encode(content)
.queryParam("sms", sms.replace(" ", "+"));
ResponseEntity<String> responseEntity = restTemplate.exchange(uriComponentsBuilder.build(false).toUriString(), HttpMethod.GET, httpEntity, String.class);
The expected query param values for those variables is:
content: "m%2F%3Da"
Special characters should be encoded, including slash (/).
sms: "TEST123+~!@%23$%25%5E%26*()_+%7B%7D:%3C%3E?"
Space should be replaced with + sign, reserved special characters should be encoded.
Using the existing code, content is encoded as expected, but sms cannot contain reserved special characters, otherwise it will give errors like "Illegal character in query at index 45:" and "Malformed escape pair at index 151: ".
I have tried other solutions:
uriComponentsBuilder.build(true).toUriString()
uriComponentsBuilder.build(false).encode().toUriString()
uriComponentsBuilder.build(true).encode().toUriString()
uriComponentsBuilder.encode().toUriString()
defaultUriBuilderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.TEMPLATE_AND_VALUES);
defaultUriBuilderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.VALUES_ONLY);
defaultUriBuilderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.URI_COMPONENT);
URLDecoder.decode
first thenencode()
Without calling encode()
, slash (/) will not be encoded, because it is a valid character. If I call encode()
, the problem is % is double encoded, so slash (/) will be %252F. If I set .build(true)
, I get errors like "Invalid character" or "Invalid encoded sequence".
Here is an example, which will encode all non-alphanumerics.
And, here is an example usage.
Output