RestTemplate不转义URL
我正在像这样成功使用Spring RestTemplate:
String url = "http://example.com/path/to/my/thing/{parameter}";ResponseEntity<MyClass> response = restTemplate.postForEntity(url, payload, MyClass.class, parameter);
那很好。
但是,有时parameter是%2F。我知道这并不理想,但事实就是如此。正确的URL应该是:http://example.com/path/to/my/thing/%2F但是,当我设置parameter为URL
时,"%2F"会被双重转义为http://example.com/path/to/my/thing/%252F。我该如何预防?
回答:
而不是使用StringURL,而是使用来构建URI一个UriComponentsBuilder。
String url = "http://example.com/path/to/my/thing/";String parameter = "%2F";
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url).path(parameter);
UriComponents components = builder.build(true);
URI uri = components.toUri();
System.out.println(uri); // prints "http://example.com/path/to/my/thing/%2F"
使用UriComponentsBuilder#build(boolean)指示
此构建器中设置的所有组件是否都已 (
false)
这或多或少等同于您自己替换{parameter}和创建URI对象。
String url = "http://example.com/path/to/my/thing/{parameter}";url = url.replace("{parameter}", "%2F");
URI uri = new URI(url);
System.out.println(uri);
然后,您可以将该URI对象用作方法的第一个参数postForObject。
以上是 RestTemplate不转义URL 的全部内容, 来源链接: utcz.com/qa/423041.html

