Get parameter names collection from Java/Android url

半腔热情 提交于 2019-12-22 05:41:32

问题


It's absolutely strange, but I can't find any Java/Android URL parser that will be compatible to return full list of parameters.

I've found java.net.URL and android.net.Uri but they are can't return parameters collection.

I want to pass url string, e.g.

String url = "http://s3.amazonaws.com/?AWSAccessKeyId=123&Policy=456&Signature=789&key=asdasd&Content-Type=text/plain&acl=public-read&success_action_status=201";

SomeBestUrlParser parser = new SomeBestUrlParser(url);
String[] parameters = parser.getParameterNames();
// should prints array with following elements
// AWSAccessKeyId, Policy, Signature, key, Content-Type, acl, success_action_status

Does anyone know ready solution?


回答1:


There is way to get collection of all parameter names.

String url = "http://domain.com/page?parameter1=value1&parameter2=value2";
List<NameValuePair> parameters = URLEncodedUtils.parse(new URI(url));
for (NameValuePair p : parameters) {
    System.out.println(p.getName());
    System.out.println(p.getValue());
}



回答2:


This static method builds map of parameters from given URL

private Map<String, String> extractParamsFromURL(final String url) throws URISyntaxException {
    return new HashMap<String, String>() {{
        for(NameValuePair p : URLEncodedUtils.parse(new URI(url), "UTF-8")) 
            put(p.getName(), p.getValue());
    }};
}

usage

extractParamsFromURL(url).get("key")




回答3:


Have a look at URLEncodedUtils




回答4:


UrlQuerySanitizer added in API level 1

        UrlQuerySanitizer sanitizer = new UrlQuerySanitizer(url_string);
        List<UrlQuerySanitizer.ParameterValuePair> list =  sanitizer.getParameterList();
        for (UrlQuerySanitizer.ParameterValuePair pair : list) {
            System.out.println(pair.mParameter);
            System.out.println(pair.mValue);
        }



回答5:


The urllib library will parse the query string parameters and allow you to access the params as either a list or a map. Use the list if there might be duplicate keys, otherwise the map is pretty handy.

Given this snippet:

String raw = "http://s3.amazonaws.com/?AWSAccessKeyId=123&Policy=456&Signature=789&key=asdasd&Content-Type=text/plain&acl=public-read&success_action_status=201";
Url url = Url.parse(raw);
System.out.println(url.query().asMap());
for (KeyValue param : url.query().params()) {
  System.out.println(param.key() + "=" + param.value());
}

The output is:

{Policy=456, success_action_status=201, Signature=789, AWSAccessKeyId=123, acl=public-read, key=asdasd, Content-Type=text/plain}
AWSAccessKeyId=123
Policy=456
Signature=789
key=asdasd
Content-Type=text/plain
acl=public-read
success_action_status=201


来源:https://stackoverflow.com/questions/12728084/get-parameter-names-collection-from-java-android-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!