None of the above answers are very good from a security standpoint. Or even just handling of special characters. The following is method we use:
/**
* @description
* Encode the URL for a GET call
*
* @param url base url to call
* @param bodyMap the paremeters to encode
* @return the encoded URL
*/
private static String encodeUrl(String url,Map<String,Object> bodyMap ) {
List<String> params = new List<String>();
for(String key : bodyMap.keySet()) {
String value = String.valueOf(bodyMap.get(key));
if(String.isNotBlank(value)) {
params.add(key+'='+EncodingUtil.urlEncode(value,'UTF-8'));
}
}
if(! params.isEmpty()) {
url += '?'+String.join(params,'&');
}
return url;
}
This still is not a great answer. In that it does not handle things like properly appending query arguments if you already have query arguments. It does not check for duplicate arguments. Give me 10 minutes and I am sure I can find another half dozen flaws.
Which is why developers should not have to write there own methods to do something this standard. It should be part of the API. In fact I still have a hard time believing it isn't, and I haven't just missed it.
5 answers