使用UriComponentsBuilder正确编码路径变量和请求参数
我正在努力使UriComponentsBuilder#queryParam
和UriComponents#expand
正确地协同工作,同时正确地编码URI的路径和查询部分中的所有特殊字符。我特别难以使用“+”字符。或者,它被双重编码为%252B
,或者根本没有编码。我需要将其正确编码,以便将ISO-8601日期作为请求参数发送
当我这样做时:
@Test
public void test {
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://www.google.com/{test}/");
Map<String, Object> expandParams = new HashMap<>();
expandParams.put("test", "junit 5");
Map<String, Object> queryParams = new HashMap<>();
queryParams.put("q", "junit+5");
for (Map.Entry<String, Object> entry : queryParams.entrySet()) {
builder = builder.queryParam(entry.getKey(), entry.getValue());
}
UriComponents uriComponents = builder.build();
if (MapUtils.isNotEmpty(expandParams)) {
uriComponents = uriComponents.expand(expandParams);
}
final URI uri = uriComponents.encode().toUri();
assertEquals("https://www.google.com/junit%205/?q=junit%2B5", uri.toString());
}
测试失败:
Expected :https://www.google.com/junit%205/?q=junit%2B5
Actual :https://www.google.com/junit%205/?q=junit+5
因此,不编码“+”符号
我知道我可以自己进行编码,并告诉build()
方法我做到了:
@Test
public void test {
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://www.google.com/{test}/");
Map<String, Object> expandParams = new HashMap<>();
expandParams.put("test", "junit 5");
Map<String, Object> queryParams = new HashMap<>();
queryParams.put("q", encodeValue("junit+5"));
for (Map.Entry<String, Object> entry : queryParams.entrySet()) {
builder = builder.queryParam(entry.getKey(), entry.getValue());
}
UriComponents uriComponents = builder.build(true);
if (MapUtils.isNotEmpty(expandParams)) {
uriComponents = uriComponents.expand(expandParams);
}
final URI uri = uriComponents.encode().toUri();
assertEquals("https://www.google.com/junit%205/?q=junit%2B5", uri.toString());
}
private static String encodeValue(String value) {
try {
return URLEncoder.encode(value, StandardCharsets.UTF_8.toString());
} catch (UnsupportedEncodingException e) {
// should not happen, we know the encoding is supported
return value;
}
}
但由于path变量,这会引发异常java.lang.IllegalArgumentException: Invalid character '{' for PATH in "/{test}/"
在这种情况下{cd4}和{cd4^}使用双编码{cd4^}
Expected :https://www.google.com/junit%205/?q=junit%2B5
Actual :https://www.google.com/junit%205/?q=junit%252B5
我尝试先扩展路径变量,然后才添加查询参数,但我也无法实现这一点
感谢您的帮助
共 (0) 个答案