I'm going to leave the actual component encoding as a user-supplied function because it is an existing well-discussed problem without a trivial JCL solution .. In any case, the following is how I would approach this particular problem without the use of third-party libraries.
While regular expressions sometimes result in two problems, I am hesitant to suggest a more strict approach such as URI because I don't know how it will - or even if it will - work with such funky invalid URLs. As such, here is a solution using a regular expression with a dynamic replacement value.
// The following pattern is pretty liberal on what it matches;
// It ought to work as long as there is no unencoded ?, =, or & in the URL
// but, being liberal, it will also match absolute garbage input.
Pattern p = Pattern.compile("\\b(\\w[^=?]*)=([^&]*)");
Matcher m = p.matcher("http://www.hello.com/bar/foo?a=,b &c =d");
StringBuffer sb = new StringBuffer();
while (m.find()) {
String key = m.group(1);
String value = m.group(2);
m.appendReplacement(sb,
encodeURIComponent(key) + "=" encodeURIComponent(value));
}
m.appendTail(sb);
See the ideone example example with a fill-in encodeURIComponent
.