How to avoid double url encoding in HATEOAS

The point is that HTTP parameters get encoded internally in HATEOAS firstly and then in spring when it requests the composed link. I will tell you a workaround in this post.

The first sign of the issue are sequences like «%2520» or «%2525» in your links. It happens this way. A space character «» becomes «%20» as expected. But then the percentage character produces «%2520» in the second event of encoding. Full table of characters to be encoded: table.

I faced this issue when used the class HalLinkDiscoverer, so the code in solution is for this class. But it can be applied more widely, you just need an opportunity to wedge in the workflow before the last event of encodind. I want to affect the mechanism of encoding without any regression.
I’m going to use a string marker — a literal which can never occur in your link (not only in the parameter).

public static final String CONST_MARKER = "__MARKER__";

In the map we don’t put the actual string, we put the marker:

Map<String, Object> params = new HashMap<>();
params.put("login", CONST_MARKER); // this param potentially contains url encoded chars, say "Bruce Lee"
HalLinkDiscoverer linkDiscoverer = new HalLinkDiscoverer();
Link link = linkDiscoverer.findLinkWithRel(FIND_BY_LOGIN_REL, getSearchLinks()).expand(params);
// fortunately we have access to the string with link
String url = link.getHref();
url = url.replace(CONST_MARKER, login); // magic happens here!
// spring will carry out the url encoding
result = restOperations.getForObject(url, Employee.class);

The issue is already reported: ticket. I have posted the workaround here as well.

You can leave a response, or trackback from your own site.

Leave a Reply

ОШИБКА: si-captcha.php plugin: Не обнаружена поддержка GD image в PHP!

Свяжитесь с вашим хостером и попросите их включить поддержку GD image для PHP.

ОШИБКА: si-captcha.php plugin: не найдена функция imagepng в PHP!

Свяжитесь с вашим хостером и попросите их включить imagepng для PHP.