Getting a collection of parameter names from Java / Android url

This is absolutely strange, but I can not find a Java / Android URL parser that will be compatible with returning a full list of parameters.

I found java.net.URL and android.net.Uri, but they cannot return a collection of parameters.

I want to pass a url string, for example.

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 a ready-made solution?

+6
source share
5 answers

There is a way to get a list 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()); } 
+12
source

This static method builds a parameter map from a 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()); }}; } 

Using

extractParamsFromURL (URL) .get ("key")

+4
source
+3
source

UrlQuerySanitizer added to 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); } 
0
source

The urllib library will analyze the query string parameters and allow you to access the parameters of both the list and the map. Use the list if there may be duplicate keys, otherwise the card is quite convenient.

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()); } 

Conclusion:

 {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 
0
source

Source: https://habr.com/ru/post/926953/


All Articles