RestTemplate: underzealous ampersand encoding

Viewed 1256

We have code like this that uses the OData to specify the resource (hardcoded with the company code here for simplicity):

String uri = "[my_endpoint]/companyprofiles.read?$filter=company/any(company:company/id eq 'C&06')";
HttpHeaders headers = getHeaders();
HttpEntity<?> requestEntity = new HttpEntity<Object>(null, headers);
ResponseEntity<CompanyProfile> respEntity =
getApiRestTemplate().exchange(uri, HttpMethod.GET, requestEntity, CompanyProfile.class);

This fails, because of an ampersand in the Company ID. It works fine with Company IDs that do not have ampersands; e.g., using 'ABCD' returns the resource as expected. Using Postman, the resource is returned if I call

[my_endpoint]/companyprofiles.read?$filter=company/any(company:company/id eq 'C%2606')

So exchange does some encoding (like spaces to %20), but does not encode ampersands, since they are usually reserved for separating URI variables.

How can I force the ampersand to be encoded? Or can I do the ampersand replacement myself and force the encoding of the percent symbol to be skipped?

EDIT: here's the final answer that worked:

String url = "http://[my_endpoint]/companyprofiles.read?$"
  +"filter=company/any(company:company/id eq '{param1}')";
Map<String, String> uriVariables = new HashMap<>();
uriVariables.put("param1", "C&06");
getApiRestTemplate().exchange(url, HttpMethod.GET, requestEntity, CompanyProfile.class, uriVariables);
1 Answers
Related