paultamalunas
paultamalunas

Reputation: 183

RestTemplate: underzealous ampersand encoding

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);

Upvotes: 2

Views: 1640

Answers (1)

fg78nc
fg78nc

Reputation: 5232

Try supplying map of parameters to overloaded exchange method to build up URI

Basically that would be something like this :

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

Upvotes: 5

Related Questions