0

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.

2 Answers 2

1

If the & character is part of the name or value in the query string then it has to be percent encoded. In the given example: contentName=abc%26def&path=Test&type=folder.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for answer.If contentName=abc & def (included spaces)then encode abc%20%26%20def so this case it is not working as excepted
As per the specification the space should get encoded as '+'. As @Trisav pointed out you can use URLEncoder (wrongly named :-)) class.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.