If we pass any type of special character we have to encode those values. Java provides a URLEncoder class for encoding any query string or form parameter into URL encoded format. When encoding URI, one of the common pitfalls is encoding the complete URI. Typically, we need to encode only the query portion of the URI.
public static void main(String[] args) {
Map<String, String> requestParameters = new LinkedHashMap<>();
requestParameters.put("contentName", "abc & def");
requestParameters.put("path", "Test");
requestParameters.put("type", "folder");
String encodedURL = requestParameters.keySet().stream()
.map(key -> key + "=" + encodeValue(requestParameters.get(key)))
.collect(Collectors.joining("&", "https://myproject.dev.com/methodology/Culture?", ""));
System.out.println(encodedURL);
}
private static String encodeValue(String value) {
String url = "";
try {
url = URLEncoder.encode(value, StandardCharsets.UTF_8.toString());
} catch (Exception ex) {
System.out.println(ex);
}
return url;
}
Output:
https://myproject.dev.com/methodology/Culture?contentName=abc+%26+def&path=Test&type=folder