package com.example;
import org.apache.http.client.utils.URIBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLDecoder; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects;
public class UriUtil {
static final Logger log = LoggerFactory.getLogger(UriUtil.class);
private UriUtil() { }
public static Map<String, String> parseQueryMap(final String uriStr) {
Map<String, String> queryPairs = new LinkedHashMap<>();
try { final URI uri = new URIBuilder(uriStr).build(); final String rawQuery = uri.getRawQuery(); log.info("CurrentUrl Query: {}", rawQuery);
if (Objects.isNull(rawQuery) || !rawQuery.contains("=")) { return queryPairs; }
final String[] pairs = rawQuery.split("&");
final String utf8 = "UTF-8";
for (String pair : pairs) {
final String deCodePair = URLDecoder.decode(pair, utf8);
if (!deCodePair.isEmpty()) { final String[] keyValue = pair.split("=");
if (2 == keyValue.length) { final String key = keyValue[0]; final String value = keyValue[1];
queryPairs.put(key, value); } } }
log.info("Parser url: {} \n parameters: {}", uri.toString(), queryPairs); return queryPairs;
} catch (URISyntaxException uriBuilderUrlException) { uriBuilderUrlException.printStackTrace(); log.warn("UriBuilder url ({}) has exception: {}", uriStr, uriBuilderUrlException.getMessage());
} catch (UnsupportedEncodingException urlDecodeException) { urlDecodeException.printStackTrace(); log.warn("Decode url ({}) query has exception: {}", uriStr, urlDecodeException.getMessage()); }
return queryPairs; } }
|