RestTemplate不能转义URL [英] RestTemplate to NOT escape url

查看:858
本文介绍了RestTemplate不能转义URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在像这样成功地使用Spring RestTemplate:

I'm using Spring RestTemplate successfully like this:

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设置为"%2F"时,它会两次转义到http://example.com/path/to/my/thing/%252F.我该如何预防?

However, sometimes parameter is %2F. I know this isn't ideal, but it is what it is. The correct URL should be: http://example.com/path/to/my/thing/%2F but when I set parameter to "%2F" it gets double escaped to http://example.com/path/to/my/thing/%252F. How do I prevent this?

推荐答案

而不是使用String URL,而是使用UriComponentsBuilder构建URI.

Instead of using a String URL, build a URI with a 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) 表示

此构建器中设置的所有组件是否均已编码(true)(false)

这或多或少等同于替换{parameter}并自己创建URI对象.

This is more or less equivalent to replacing {parameter} and creating a URI object yourself.

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方法的第一个参数.

You can then use this URI object as the first argument to the postForObject method.

这篇关于RestTemplate不能转义URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆