Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

java - RestTemplate to NOT escape url

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);

And that is good.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"

Use UriComponentsBuilder#build(boolean) to indicate

whether all the components set in this builder are encoded (true) or not (false)

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);

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...