【发布时间】:2018-10-20 13:48:25
【问题描述】:
我有一个 Spring 应用程序接收像 http://localhost/foo?email=foo+bar@example.com 这样的请求。这会触发一个大致如下所示的控制器:
@RestController
@RequestMapping("/foo")
public class FooController extends Controller {
@GetMapping
public void foo(@RequestParam("email") String email) {
System.out.println(email)
}
}
当我可以访问email 时,它已被转换为foo bar@example.com,而不是原来的foo+bar@example.com。根据When to encode space to plus (+) or %20?,这应该只发生在内容为application/x-www-form-urlencoded 的请求中。我的请求的内容类型为application/json。请求的完整 MIME 标头如下所示:
=== MimeHeaders ===
accept = application/json
content-type = application/json
user-agent = Dashman Configurator/0.0.0-dev
content-length = 0
host = localhost:8080
connection = keep-alive
为什么 Spring 将加号解码为空格?如果这是它应该工作的方式,why isn't it encoding pluses as %2B when making requests?
我发现了这个错误报告:https://jira.spring.io/browse/SPR-6291,这可能暗示这已在 3.0.5 版本上得到修复,并且我正在使用 Spring > 5.0.0。我可能会误解错误报告的某些内容。
我还发现了有关 RestTemplate 处理这些值的讨论:https://jira.spring.io/browse/SPR-5516(我的客户正在使用 RestTemplate)。
所以,我的问题是,Spring 为什么要这样做?我怎样才能禁用它?我应该禁用它还是应该在客户端上编码加号,即使请求是 json?
澄清一下,我在这里既没有使用 HTML 也没有使用 JavaScript。有一个 Spring Rest 控制器,客户端是 Spring 的 RestTemplate 和 UriTemplate 或 UriComponentsBuilder,它们都没有像 Spring 解码那样对加号进行编码。
【问题讨论】:
-
我认为解码是正确的,如果您想发送
+作为值的一部分,您不应该发送%2b。+意味着成为space,这就是你在这里得到的。您发布的问题是关于 url 解析而不是参数解析 -
@TarunLalwani:
+表示application/x-www-form-urlencoded中的空格。我正在发送application/json,其中 + 没有特定含义。 -
您正在混合两件事,请求正文中的
+意味着当标头有application/x-www-form-urlencoded时有一个空格。到目前为止,我们讨论的是 url,而 url 根本不需要依赖content-type? -
另外,如果你想改变我相信你需要像stackoverflow.com/a/28214811/2830850一样配置过滤器
-
@TarunLalwani:据我所知,URI RFC 没有提到
+需要编码为%2b: tools.ietf.org/html/rfc3986。这是在 HTML4 中定义的:w3.org/TR/html4/interact/forms.html#h-17.13.4.1。此错误报告是相关的:jira.spring.io/browse/SPR-6296。同样,我在这里可能会感到困惑,我明白你为什么 URL 会依赖于内容类型。
标签: spring url encoding resttemplate