'How to read query param value if special character (&) part of query param value
Url: https://myproject.dev.com/methodology/Culture?contentName=abc & def&path=Test&type=folder
Need to fetch only query params from above URL but problem is '&' in contentName=abc & def so while fetching the contentName getting the value in two parts like abc, def.
Please suggest the approach to get contentName is abc & def instead of abc,def.
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
