RestTemplate:不热心的符号编码
RestTemplate: underzealous ampersand encoding
我们有这样的代码,它使用 OData 来指定资源(为简单起见,在此处使用公司代码进行硬编码):
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);
这失败了,因为公司 ID 中有一个 & 号。它适用于没有 & 符号的公司 ID;例如,按预期使用 'ABCD' returns 资源。使用邮递员,如果我调用
则返回资源
[my_endpoint]/companyprofiles.read?$filter=company/any(company:company/id eq 'C%2606')
所以 exchange 会进行一些编码(例如空格到 %20),但不会对 & 符号进行编码,因为它们通常保留用于分隔 URI 变量。
如何强制对“&”符号进行编码?或者我可以自己替换 & 符号并强制跳过百分号的编码吗?
编辑:这是有效的最终答案:
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);
尝试向 overloaded exchange method 提供参数映射以构建 URI
基本上是这样的:
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);
我们有这样的代码,它使用 OData 来指定资源(为简单起见,在此处使用公司代码进行硬编码):
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);
这失败了,因为公司 ID 中有一个 & 号。它适用于没有 & 符号的公司 ID;例如,按预期使用 'ABCD' returns 资源。使用邮递员,如果我调用
则返回资源[my_endpoint]/companyprofiles.read?$filter=company/any(company:company/id eq 'C%2606')
所以 exchange 会进行一些编码(例如空格到 %20),但不会对 & 符号进行编码,因为它们通常保留用于分隔 URI 变量。
如何强制对“&”符号进行编码?或者我可以自己替换 & 符号并强制跳过百分号的编码吗?
编辑:这是有效的最终答案:
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);
尝试向 overloaded exchange method 提供参数映射以构建 URI
基本上是这样的:
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);