Last active
July 2, 2024 05:30
-
-
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
import com.google.common.base.Charsets; | |
import com.google.common.base.Joiner; | |
import com.google.common.base.Splitter; | |
import com.google.common.base.Strings; | |
import com.google.common.collect.Lists; | |
import com.google.common.collect.Maps; | |
import java.io.UnsupportedEncodingException; | |
import java.net.URLDecoder; | |
import java.net.URLEncoder; | |
import java.util.Collections; | |
import java.util.List; | |
import java.util.Map; | |
/** | |
* @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