Skip to content

Instantly share code, notes, and snippets.

@KonstantinBerkow
Last active February 11, 2018 13:52
Show Gist options
  • Save KonstantinBerkow/c34baf703fe8e8a7208cfdd7cbcf0a81 to your computer and use it in GitHub Desktop.
Save KonstantinBerkow/c34baf703fe8e8a7208cfdd7cbcf0a81 to your computer and use it in GitHub Desktop.
package me.berkow.playground;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Formatter;
import java.util.Iterator;
import java.util.Map;
private static String encodedUrl(String baseUrl,
String path, Object[] pathParams,
Map<String, Object> query) throws UnsupportedEncodingException {
StringBuilder builder = new StringBuilder(baseUrl);
Formatter formatter = new Formatter(builder);
formatter.format(path, pathParams);
Iterator<Map.Entry<String, Object>> iterator = query.entrySet().iterator();
if (!iterator.hasNext()) {
return builder.toString();
}
final String utf8 = StandardCharsets.UTF_8.name();
Map.Entry<String, Object> entry = iterator.next();
String key = entry.getKey();
Object value = entry.getValue();
String encodedValue = value == null ? null : URLEncoder.encode(value.toString(), utf8);
if (encodedValue != null) {
formatter.format("?%s=%s", key, encodedValue);
} else {
formatter.format("?%s", key);
}
while (iterator.hasNext()) {
entry = iterator.next();
key = entry.getKey();
value = entry.getValue();
encodedValue = value == null ? null : URLEncoder.encode(value.toString(), utf8);
if (encodedValue != null) {
formatter.format("&%s=%s", key, encodedValue);
} else {
formatter.format("&%s", key);
}
}
return builder.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment