在调用Spring RestController时,使用Spring的RestTemplate转义URL变量的正确方法是什么?

时间:2018-05-20 06:48:37

标签: spring resttemplate

调用RestTemplate.exchange来执行get请求时,例如:

String foo = "fo+o";
String bar = "ba r";
restTemplate.exchange("http://example.com/?foo={foo}&bar={bar}", HttpMethod.GET, null, foo, bar)

为get请求正确转义URL变量的正确之处是什么?

具体来说,我如何正确地转义(+)因为Spring is interpreting as spaces,所以我需要对它们进行编码。

我尝试使用UriComponentsBuilder这样:

String foo = "fo+o";
String bar = "ba r";
UriComponentsBuilder ucb = UriComponentsBuilder.fromUriString("http://example.com/?foo={foo}&bar={bar}");
System.out.println(ucb.build().expand(foo, bar).toUri());
System.out.println(ucb.build().expand(foo, bar).toString());
System.out.println(ucb.build().expand(foo, bar).toUriString());
System.out.println(ucb.build().expand(foo, bar).encode().toUri());
System.out.println(ucb.build().expand(foo, bar).encode().toString());
System.out.println(ucb.build().expand(foo, bar).encode().toUriString());
System.out.println(ucb.buildAndExpand(foo, bar).toUri());
System.out.println(ucb.buildAndExpand(foo, bar).toString());
System.out.println(ucb.buildAndExpand(foo, bar).toUriString());
System.out.println(ucb.buildAndExpand(foo, bar).encode().toUri());
System.out.println(ucb.buildAndExpand(foo, bar).encode().toString());
System.out.println(ucb.buildAndExpand(foo, bar).encode().toUriString());

并打印出来:

http://example.com/?foo=fo+o&bar=ba%20r
http://example.com/?foo=fo+o&bar=ba r
http://example.com/?foo=fo+o&bar=ba r
http://example.com/?foo=fo+o&bar=ba%20r
http://example.com/?foo=fo+o&bar=ba%20r
http://example.com/?foo=fo+o&bar=ba%20r
http://example.com/?foo=fo+o&bar=ba%20r
http://example.com/?foo=fo+o&bar=ba r
http://example.com/?foo=fo+o&bar=ba r
http://example.com/?foo=fo+o&bar=ba%20r
http://example.com/?foo=fo+o&bar=ba%20r
http://example.com/?foo=fo+o&bar=ba%20r

在某些情况下,空间被正确转义,但加号永远不会被转义。

我也试过UriTemplate这样:

String foo = "fo+o";
String bar = "ba r";
UriTemplate uriTemplate = new UriTemplate("http://example.com/?foo={foo}&bar={bar}");
Map<String, String> vars = new HashMap<>();
vars.put("foo", foo);
vars.put("bar", bar);
URI uri = uriTemplate.expand(vars);
System.out.println(uri);

具有完全相同的结果:

http://example.com/?foo=fo+o&bar=ba%20r

5 个答案:

答案 0 :(得分:14)

显然,正确的方法是定义工厂并更改编码模式:

String foo = "fo+o";
String bar = "ba r";
DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory();
factory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.VALUES_ONLY);
URI uri = factory.uriString("http://example.com/?foo={foo}&bar={bar}").build(foo, bar);
System.out.println(uri);

打印出来:

http://example.com/?foo=fo%2Bo&bar=ba%20r

此处记录了这些内容:https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#web-uri-encoding

答案 1 :(得分:9)

我认为您的问题是RFC 3986UriComponentsUriTemplate所基于的{em>不要求{{1}的转义在查询字符串中。

规范的观点很简单:

+

如果您的Web框架(例如Spring MVC!)将sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" pchar = unreserved / pct-encoded / sub-delims / ":" / "@" query = *( pchar / "/" / "?" ) URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ] 解释为空格,则这是它的决定,而不是URI规范下的要求。

参考上述内容,您还会看到+未对!$'()*+,;进行转义。 UriTemplate= 已被转义,因为Spring采取了一种“自我约束”的观点。查询字符串的外观 - 一系列键=值对。

同样,&和空白 是转义的,因为它们在规范下的查询字符串中是非法的。

当然,如果您非常合理地希望查询参数被转义,这一切都不会给您带来任何安慰!

要对查询参数进行实际编码,以便您的Web框架可以容忍它们,您可以使用类似#[]的内容。

答案 2 :(得分:6)

我开始相信这是一个错误,我在此报告:https://jira.spring.io/browse/SPR-16860

目前,我的解决方法是:

String foo = "fo+o";
String bar = "ba r";
String uri = UriComponentsBuilder.
    fromUriString("http://example.com/?foo={foo}&bar={bar}").
    buildAndExpand(vars).toUriString();
uri = uri.replace("+", "%2B"); // This is the horrible hack.
try {
    return new URI(uriString);
} catch (URISyntaxException e) {
    throw new RuntimeException("UriComponentsBuilder generated an invalid URI.", e);
}

这是一个可怕的黑客,在某些情况下可能会失败。

答案 3 :(得分:5)

对于这个,我仍然希望使用适当的方法解决编码,而不是像你一样使用Hack。我会使用类似下面的内容

String foo = "fo+o";
String bar = "ba r";
MyUriComponentsBuilder ucb = MyUriComponentsBuilder.fromUriString("http://example.com/?foo={foo}&bar={bar}");

UriComponents uriString = ucb.buildAndExpand(foo, bar);
// http://example.com/?foo=fo%252Bo&bar=ba+r
URI x = uriString.toUri();

// http://example.com/?foo=fo%2Bo&bar=ba+r
String y = uriString.toUriString();

// http://example.com/?foo=fo%2Bo&bar=ba+r
String z = uriString.toString();

当然,课程如下所示

class MyUriComponentsBuilder extends UriComponentsBuilder {
    protected UriComponentsBuilder originalBuilder; 

    public MyUriComponentsBuilder(UriComponentsBuilder builder) {
        // TODO Auto-generated constructor stub
        originalBuilder = builder;
    }


    public static MyUriComponentsBuilder fromUriString(String uri) {
        return new MyUriComponentsBuilder(UriComponentsBuilder.fromUriString(uri));
    }


    @Override
    public UriComponents buildAndExpand(Object... values) {
        // TODO Auto-generated method stub
        for (int i = 0; i< values.length; i ++) {
            try {
                values[i] = URLEncoder.encode((String) values[i], StandardCharsets.UTF_8.toString());
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return originalBuilder.buildAndExpand(values);
    }

}

仍然不是最干净的方式,但更好的是做一个硬编码的替换方法

答案 4 :(得分:2)

你可以在Spring中使用UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder)

String url = UriComponentsBuilder
    .fromUriString("http://example.com/")
    .queryParam("foo", "fo+o")
    .queryParam("bar", "ba r")
    .build().toUriString();

restTemplate.exchange(url , HttpMethod.GET, httpEntity);