我有三种解决方案,第三种是博卓的改进版。
首先,如果你不想自己写东西而只是使用一个lib,那么使用Apache的httpcomponents lib的URIBuilder类:http ://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/ http/client/utils/URIBuilder.html
new URIBuilder("http://...").getQueryParams()...
第二:
// overwrites duplicates
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
public static Map<String, String> readParamsIntoMap(String url, String charset) throws URISyntaxException {
Map<String, String> params = new HashMap<>();
List<NameValuePair> result = URLEncodedUtils.parse(new URI(url), charset);
for (NameValuePair nvp : result) {
params.put(nvp.getName(), nvp.getValue());
}
return params;
}
第三:
public static Map<String, List<String>> getQueryParams(String url) throws UnsupportedEncodingException {
Map<String, List<String>> params = new HashMap<String, List<String>>();
String[] urlParts = url.split("\\?");
if (urlParts.length < 2) {
return params;
}
String query = urlParts[1];
for (String param : query.split("&")) {
String[] pair = param.split("=");
String key = URLDecoder.decode(pair[0], "UTF-8");
String value = "";
if (pair.length > 1) {
value = URLDecoder.decode(pair[1], "UTF-8");
}
// skip ?& and &&
if ("".equals(key) && pair.length == 1) {
continue;
}
List<String> values = params.get(key);
if (values == null) {
values = new ArrayList<String>();
params.put(key, values);
}
values.add(value);
}
return params;
}