How to encode "@" sign using UriComponentsBuilder

Viewed 42

This issue is about a HTTP PUT request. I'm passing my url, query parameters and body to a method called buildURI().

private URI buildURI(String url, Map<String, Object> queryParameters, T body) {
        try {
            String bodyString = null;
            if (body != null) {
                bodyString = objectMapper.writeValueAsString(body);
            }

        } catch (JsonProcessingException e) {
            System.out.println(e);
        }

        UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(url);
        if ((queryParameters != null) && (!queryParameters.isEmpty())) {
            queryParameters.forEach((a, b) -> uriComponentsBuilder.queryParam(a, b));
        }

        return uriComponentsBuilder.encode().buildAndExpand().toUri();
    }

The presence of reserved characters(& = %) can prevent correct parsing of the URI string. To substitute those characters I used this UriComponentsBuilder.fromUriString(url). Problem is those character list does not contain "@".

My url is http://1.1.1.1:1111/xx/xx/save/abc@gmail.com. I need to substitute @ as well.

But if I encode @ and then call buildURI() this gives the url as http://1.1.1.1:1111/xx/xx/save/abc%2540gmail.com. (because of double encoding)

Calling this buildURI() is a must since I'm using common code. I need to anyhow encode this "@" and get the url as http://1.1.1.1:1111/xx/xx/save/abc%40gmail.com.

Please give me a solution.

0 Answers
Related