Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
StringUtils – common utility methods for Java
/**
* @author Joni Karppinen
* Licence: WTFPL, http://www.wtfpl.net/txt/copying/
*/
public class StringUtils {
public static String encodeUrlParameters(Map<String, String> parameters) {
if (parameters == null || parameters.isEmpty()) {
return "";
}
List<String> nameValuePairs = Lists.newArrayList();
for (Map.Entry<String, String> entry : parameters.entrySet()) {
nameValuePairs.add(entry.getKey() + "=" + urlEncode(entry.getValue()));
}
return "?" + Joiner.on("&").join(nameValuePairs);
}
public static Map<String, String> decodeUrlParameters(String paramString) {
if (Strings.isNullOrEmpty(paramString)) {
return Collections.emptyMap();
}
if (paramString.startsWith("?")) {
paramString = paramString.substring(1);
}
Map<String, String> result = Maps.newLinkedHashMap();
for (String nameValue : Splitter.on("&").trimResults().split(paramString)) {
String[] parts = nameValue.split("=");
result.put(parts[0], urlDecode(parts[1]));
}
return result;
}
public static String urlEncode(String string) {
try {
return URLEncoder.encode(string, Charsets.UTF_8.name());
}
catch (UnsupportedEncodingException e) { // UTF-8 should always be supported
throw new RuntimeException("URLEncoder.encode() failed");
}
}
public static String urlDecode(String string) {
try {
return URLDecoder.decode(string, Charsets.UTF_8.name());
}
catch (UnsupportedEncodingException e) { // UTF-8 should always be supported
throw new RuntimeException("URLDecoder.decode() failed");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment