下面提到的是我的requestUrl “http://localhost:80/v1/accounts/60a362bd6b84a37effc8f5a3/name/QA 分析师” 我正在使用以下代码
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(requestUrl);
ResponseEntity<RoleResponse> responseEntity = null;
HttpEntity<?> entity = new HttpEntity(RestUtil.getHeaders(this.appSecret));
try {
responseEntity = this.restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, RoleResponse.class, new Object[0]);
} catch (Exception var9) {
log.error("Error occurred while getting role by name for accountId {}", accountId, var9);
throw new RestClientException("rest_client_exception", "Unable to get role by name for account");
}
在使用 java 8 版本在端口 80 上运行的服务中,我可以看到以下 uri 被命中 “v1/账户/60a362bd6b84a37effc8f5a3/名称/QA%2520Analyst” 但是这个 uri 正在被处理并且可以获得响应代码 200。 现在我迁移到 java 17 并且请求抛出 400 BAD_REQUEST。 这是什么原因?我该如何处理? 我使用的restTemplate是org.springframework.web.client
请求 URI 中包含空格是一种不好的做法。检查这个answer,了解为什么 URL 不应包含文字空格。我认为您的情况的问题是空格字符被编码两次。空格字符的 URL 编码为
%20
,而 %
字符则编码为 %25
。因此,您的 URL 会被编码两次为 %2520
。我怀疑 builder.toUriString()
可能对其进行一次编码,然后在 restTemplate.exchange()
中进行另一个编码。我不确定,但很可能其中一个实现在 Java 17 中发生了变化,这就是为什么在 URI 中包含空格是一个糟糕的想法和设计。我宁愿将其作为查询参数,以确保大多数字符的安全编码。
http://localhost:80/v1/accounts/{accountId}?name=QA%20Analyst
RESTful API 设计的一个良好实践是,路径参数用于标识特定资源,而查询参数用于对这些资源进行排序/过滤。就您而言,您似乎正在按名称进行过滤/搜索。