Get parameter names collection from Java/Android url - java

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?

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

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")

Have a look at URLEncodedUtils

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

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

Related

Rebuilding a URL without a query string parameter

Let's say I have a page which lists things and has various filters for that list in a sidebar. As an example, consider this page on ebuyer.com, which looks like this:
Those filters on the left are controlled by query string parameters, and the link to remove one of those filters contains the URL of the current page but without that one query string parameter in it.
Is there a way in JSP of easily constructing that "remove" link? I.e., is there a quick way to reproduce the current URL, but with a single query string parameter removed, or do I have to manually rebuild the URL by reading the query string parameters, adding them to the base URL, and skipping the one that I want to leave out?
My current plan is to make something like the following method available as a custom EL function:
public String removeQueryStringParameter(
HttpServletRequest request,
String paramName,
String paramValue) throws UnsupportedEncodingException {
StringBuilder url = new StringBuilder(request.getRequestURI());
boolean first = true;
for (Map.Entry<String, String[]> param : request.getParameterMap().entrySet()) {
String key = param.getKey();
String encodedKey = URLEncoder.encode(key, "UTF-8");
for (String value : param.getValue()) {
if (key.equals(paramName) && value.equals(paramValue)) {
continue;
}
if (first) {
url.append('?');
first = false;
} else {
url.append('&');
}
url.append(encodedKey);
url.append('=');
url.append(URLEncoder.encode(value, "UTF-8"));
}
}
return url.toString();
}
But is there a better way?
The better way is to use UrlEncodedQueryString.
UrlEncodedQueryString can be used to set, append or remove parameters
from a query string:
URI uri = new URI("/forum/article.jsp?id=2&para=4");
UrlEncodedQueryString queryString = UrlEncodedQueryString.parse(uri);
queryString.set("id", 3);
queryString.remove("para");
System.out.println(queryString);

How to avoid interference of HttpServletRequest.getReader and getParameterValues?

In my application I have to extract parameters of a request and put into a collection in the order of their appearance in the querystring.
For example, if the sender makes following request,
http://myapp.com/myrequest?param3=value3&param2=value2&param1=value1 ,
I need to generate a collection, in which the elements are placed in this order: param3, param2, param1.
To achieve this, I first extract the names of the parameters using the method getParameterNames shown below.
private List<String> getParameterNames(HttpServletRequest aRequest)
throws IOException {
final List<String> parameterNames = new LinkedList<>();
final BufferedReader reader = aRequest.getReader();
final String queryString = IOUtils.toString(reader);
final String[] parameterValuePairs = queryString.split("&");
for (String parameterValuePair : parameterValuePairs) {
final String[] nameValueArray = parameterValuePair.split("=");
parameterNames.add(nameValueArray[0]);
}
return parameterNames;
}
The problem: After invokation of this method, aRequest.getParameterValue(...) returns null for ever parameter name.
If I do it otherwise - first save the parameter map, and then invoke getParameterNames, then its result is null.
final Map<String,String[]> parameterMap = aRequest.getParameterMap();
final List<String> parameterNames = getParameterNames(aRequest);
I tried following things:
Make sure that reader.close() is not invoked in getParameterNames (elsewhere I read that this may cause problems).
Invoke reader.reset().
None of this helped.
How can I get a list of parameter-value pairs from a HttpServletRequest, which is sorted by parameter's appearance in the querystring?
With the first approach you don't need to use Reader to get the parameters. Instead do:
final List<String> parameterNames = new LinkedList<>();
final String queryString = query.getQueryString(); // get query string from query itself
// rest of your code stays unchanged
The reason it didn't work is because data from a request input stream can be read only once.
Or, if I am wrong and that is not the case, you can save parameters and their values into a LinkedHashMap:
final LinkedHashMap<String, String> parameterValues = new LinkedHashMap<>();
final BufferedReader reader = aRequest.getReader();
final String queryString = IOUtils.toString(reader);
final String[] parameterValuePairs = queryString.split("&");
for (String parameterValuePair : parameterValuePairs) {
final String[] nameValueArray = parameterValuePair.split("=");
parameterValues.put(nameValueArray[0], nameValueArray[1]);
}
Now parameterValues is a map with entries sorted by the order of appearance.

How to parse a deep URL using jQuery params()?

Building an Android app that needs to parse a URL built with deep parameters using jQuery params().
Sample URL:
http://webapp.example.com/#params%5Bid%5D=33330&type=detail&channel=ss&view=Detail
The result should be JSON, which I can feed into Gson. Manual parsing is not optimal; a generic solution is preferable.
How can this task be done?
at first glance I thought you need a js/jquery solution. But on closer inspection, probably java. Anywhoo, I had already dont the former so you get both!
Js/jquery
url="http://webapp.example.com/#params%5Bid%5D=33330&type=detail&channel=ss&view=Detail";
delimatedString = url.substring(url.indexOf("#")+1,url.length); //remove everything before the #
var jsonObject = new Object();
$.each(delimatedString.split("&"), function(index, item) {//for loop to spit at the *&
//item is now in the syntax key=value
var keyValPair = item.split("="); //split each item at the = to seperate
var key = keyValPair[0];
var value = keyValPair[1];
jsonObject[key]=value;
});
java
String delimatedStrings = url.substring("&"+1, url.length)
String[] keyValuePairs = delimatedString.split("&");
Map<String, String> map = new HashMap<String, String>();
for (String keyValuePair : keyValuePairs)
{
String key = delimatedString.split("=")[0];
String value = delimatedString.split("=")[1];
map.put(key, value);
}
ps. I didnt compile the java, and you will need an external lib to take care of the map to JSON conversion.

handle exclusive parameter java servlet

My html page sends only one parameter. I need to handle it and send a response. This code handles more than one parameter and in my case is not so good:
Enumeration<?> paramNames = request.getParameterNames();
while (paramNames.hasMoreElements()) {
String paramName = (String) paramNames.nextElement();
}
But how I can modify this code if I have only one parameter and do not know its name.
Thanks!
Try something like this.
Map<String,String[]> paramMap = request.getParameterMap();
String myValue = paramMap.get(paramMap.keySet().iterator().next())[0];

how to check if a parameter is present in a URL in simplest form

I would like to parse a string which is basically a URL. I need to check simply that a parameters is passed to it or not.
so http://a.b.c/?param=1 would return true http://a.b.c/?no=1 would return false and http://a.b.c/?a=1&b=2.....&param=2 would return true since param is set
I am guessing that it would involve some sort of regular expression.
Java has a builtin library for handling urls: Spec for URL here.
You can create a URL object from your string and extract the query part:
URL url = new URL(myString);
String query = url.getQuery();
Then make a map of the keys and values:
Map params<string, string> = new HashMap<string, string>();
String[] strParams = query.split("&");
for (String param : strParams)
{
String name = param.split("=")[0];
String value = param.split("=")[1];
params.put(name, value);
}
Then check the param you want with params.containsKey(key);
There is probably a library out there that does all this for you though, so have a look around first.
String url = "http://a.b.c/?a=1&b=2.....&param=2";
String key = "param";
if(url.contains("?" + key + "=") || url.contains("&" + key + "="))
return true;
else
return false;

Categories

Resources