url encoding in java has issue with apostrophe and space

I have the lastname as “Mc’ Donald” and I am trying to encode in such a way that it works. Like the encoded value at the end should have %27+ for apostrophe and space. With this code, it is encoding to “%2527”. in db, I have Mc’ Donald so I am replacing first to encode the whole thing in the next line.

lastName = lastName.replace("'", "'");
HttpEntity<String> entity = new HttpEntity<>(getHttpHeaders());
UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(baseUrl + "/idsearch").queryParam("lastname", URLEncoder.encode(lastName, "UTF-8")).queryParam("dateOfBirth", birthday);
 ResponseEntity<Response> result = restTemplate.exchange(uriBuilder.toUriString(),
                    HttpMethod.GET, entity, Response.class);

How do I get the code to work by encoding apostrophe and space to %27+ or %27%20?

Answer

You don’t need to do URL-encoding for values supplied to UriComponentsBuilder.queryParam method. It already knows to URL-encode your queryParam

Just do this:

lastName = lastName.replace("&apos;", "'");
HttpEntity<String> entity = new HttpEntity<>(getHttpHeaders());
UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(baseUrl + "/idsearch").queryParam("lastname",lastName).queryParam("dateOfBirth", birthday);
 ResponseEntity<Response> result = restTemplate.exchange(uriBuilder.toUriString(),
                    HttpMethod.GET, entity, Response.class);