Last active
August 29, 2015 14:20
-
-
Save jonikarppinen/b202f5d49e32aa840db2 to your computer and use it in GitHub Desktop.
StringUtils – common utility methods for Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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