使用UriComponentsBuilder在Spring中替换空格为%20

3

我有一个方法,它接受一些参数并从中形成URI以访问我们的客户端REST服务。其中一个参数可能是一个空格。问题在于UriComponentsBuilder.pathSegment会忽略空格。因此,假设有'v1',' ','v2'...将形成URI .../v1/v2 而不是 /v1/%20/v2。如果我直接传递%20给pathSegment,它将被替换为%2520。这是我的函数:

 private String getJsonStringFromDetranRestParams(String url, String... params) {

    URI targetUrl = UriComponentsBuilder.fromUriString(url).pathSegment(params).build().encode().toUri();
    String json = restTemplate.getForObject(targetUrl, String.class);

    return json;
}

有没有类似于“转义字符”的功能,使得函数可以将%20视为有效字符串而不是特殊字符串。我正在寻找Java中的\\等效功能。

2个回答

3

只需使用build()将其作为字符串返回,pathSegment中的空格将被忽略,您必须传递%20

String targetUrl = UriComponentsBuilder.fromUriString("http://localhost:8080").pathSegment("v1","%20","v2").build().toUriString();
System.out.println(targetUrl);  //http://localhost:8080/v1/%20/v2

或者使用build(true)进行编码

 URI targetUrl = UriComponentsBuilder.fromUriString("http://localhost:8080").pathSegment("v1","%20","v2").build(true).toUri();
System.out.println(targetUrl); ////http://localhost:8080/v1/%20/v2

0

使用UriComponentsBuilder正确的方法如下:

UriComponentsBuilder.fromUriString("http://localhost:8080").encode().build().toUri()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接