Can someone tell me how can I get query parameters from a url in java that may contain ampersand in their values?

Viewed 30

For example for the url http:localhost:8080?v1=a&v2=b&c&v3=d I need in this case. v1=a v2=b&c v3=d I want to do this in java only. Thanks

1 Answers

You must use URLEncoder.encode to encode your param like this:

private String encodeValue(String value) {
    return URLEncoder.encode(value, StandardCharsets.UTF_8.toString());
}

public void callAPI() {
    Map<String, String> requestParams = new HashMap<>();
    requestParams.put("v1", "a");
    requestParams.put("v2", "b&c");
    requestParams.put("v3", "d");

    String encodedURL = requestParams.keySet().stream()
      .map(key -> key + "=" + encodeValue(requestParams.get(key)))
      .collect(joining("&", "http:localhost:8080?", ""));

    // call api with encodedURL
}

Then when you get your params, you use URLDecoder.decode to decode your param:

URLDecoder.decode(yourParam, StandardCharsets.UTF_8.toString());

Hope this help!

Related