johnny-b-goode
johnny-b-goode

Reputation: 3893

Spring Web REST call special characters encoding

I am having troubles transferring strings, containing special characters from one java service to another java service. Here's what's happening. On the 'client' im having a following call:

final String url = baseUrl() + "/getOrders";
final UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
builder.queryParam("username", username);

final ResponseEntity<TResponse> restResp = restTemplate.exchange(builder.build().toString(), HttpMethod.GET, entity, OrdersResult.class);

On a 'server' side there is a method with a following signature:

@RequestMapping(value = "getOrders", method = RequestMethod.GET)
public OrdersResult getOrders(@RequestParam(value = "username") String username)

The problem is that if username contains any special character, like '+' or '|', username string gets to server with a white spaces instead of an actual character. For instance:

"I+Am|A+User" -> "I Am A User"

I can fix it by manually encode url parameter on client:

builder.queryParam("username", URLEncoder.encode(username, 'UTF-8'));

and then decode on server.

Is there any way to avoid manual encoding/decoding?

Upvotes: 0

Views: 1466

Answers (1)

Semyon Kirekov
Semyon Kirekov

Reputation: 1442

On a browser side query params are usually encoded with encodeUriComponent. So, the special characters can be transferred correctly. Then the server application decodes the string to original value.

Therefore, I see no problems with the approach you proposed.

Upvotes: 1

Related Questions