How to parse a uri with parameters into a Map in Java - java

I want to parse the following:
full_uri= "path/for/uri?$param1=value1&$param2=value2
in a way that gives me the uri as a string and the parameters as a map. What I'm trying right now is:
String[] full_uri_split = full_uri.split("\\?");
String uri = full_uri_split[0];
String parameters = full_uri_split[1];
This gives me 2 variables, 1 that is the uri, and another that is a string containing all the parameters, in the format of:
parameters = "$param1=value1&$param2=value2"
My next best guess is to then split it on the & signs:
String parameters_split = parameters.split("&");
which returns:
["$param1=value1", "$param2=value2"]
Now I want to convert this into a Map that looks like so:
"param1":"value1",
"param2":"value2"
and I'm not sure how to go about it.
I'm sure I could get it to work by doing more splits, but it seems horribly inefficient. So essentially, I want to turn:
full_uri = "path/for/uri?$param1=value1&$param2=value2"
into
uri = "path/for/uri"
params = {
"param1": "value1",
"param2": "value2"
}

Here is a solution using a loop.
Map<String, String> params = new HashMap<>();
for (String s : parameters_split){
params.put(s.split("=")[0], s.split("=")[1]);
}

Related

How to parse query param effectively in java?

All I have is the request URI from which I have to parse the query params. What I'm doing is adding them to json/hashmap and fetching again like the following
String requestUri = "name=raju&school=abcd&college=mnop&color=black&fruit=mango";
All I have to do is to finally assign it to variables like the following
String name = "raju";
String school = "abcd";
String college = "mnop";
String color = "black";
String fruit = "mango";
So I am parsing the request uri like the following
String[] paramsKV = requestUri.split("&");
JSONArray jsonKVArr = new JSONArray();
for (String params : paramsKV) {
String[] tempArr = params.split("=");
if(tempArr.length>1) {
String key = tempArr[0];
String value = tempArr[1];
JSONObject jsonObj = new JSONObject();
jsonObj.put(key, value);
jsonKVArr.put(jsonObj);
}
}
The another way is to populate the same in hash map and obtain the same. The other way is to match the requestUri string with regex pattern and obtain the results.
Say for an example to get the value of school I have to match the values between the starting point of the string school and the next & - which doesn't sound good.
What is the better approach to parse the query String in java?
How could i handle the following thing in a better way?
I need to construct another hash map like the following from the above results like
Map<String, String> resultMap = new HashMap<String, String>;
resultMap.put("empname", name);
resultMap.put("rschool", school);
resultMap.put("empcollege", college);
resultMap.put("favcolor", color);
resultMap.put("favfruit", fruit);
To make it simple all I have to do is to parse the query param and construct a hashMap by naming the key filed differently. How could I do it in a simple way? Any help in this is much appreciated.
Short answer: Every HTTP Client library will do this for you.
Example: Apache HttpClient's URLEncodedUtils class
String queryComponent = "name=raju&school=abcd&college=mnop&color=black&fruit=mango";
List<NameValuePair> params = URLEncodedUtils.parse(queryComponent, Charset.forName("UTF-8"));
They're basically approaching it the same way. Parameter key-value pairs are delimited by & and the keys from the values by = so String's split is appropriate for both.
From what I can tell however your hashmap inserts are mapping new keys to the existing values so there's really no optimization, save maybe for moving to a Java 8 Stream for readability/maintenance and/or discarding the initial jsonArray and mapping straight to the hashmap.
Here is another possible solution:
Pattern pat = Pattern.compile("([^&=]+)=([^&]*)");
Matcher matcher = pat.matcher(requestUri);
Map<String,String> map = new HashMap<>();
while (matcher.find()) {
map.put(matcher.group(1), matcher.group(2));
}
System.out.println(map);
You can use Java 8 and store your data in HashMap in one operation.
Map<String,String> map = Pattern.compile("\\s*&\\s*")
.splitAsStream(requestUri.trim())
.map(s -> s.split("=", 2))
.collect(Collectors.toMap(a -> a[0], a -> a.length > 1 ? a[1]: ""));
You can do it by Jersey library (com.sun.jersey.api.uri.UriComponent or org.glassfish.jersey.uri.UriComponent class):
String queryComponent = "name=raju&school=abcd&college=mnop&color=black&fruit=mango";
MultivaluedMap<String, String> params = UriComponent.decodeQuery(queryComponent, true);
Use jackson json parser. Maven dependency:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>
Now use ObjectMapper to create Map from json string:
ObjectMapper mapper = new ObjectMapper();
Map list = mapper.readValue(requestUri, Map.class);

String to map conversion java

Code:
Map test = new HashMap<String,String>();
test.put("1", "erica");
test.put("2", "frog");
System.out.println(test.toString());
This code gives output as :
{1=erica, 2=frog}
I want this output to be again put in a map as key value-pair .
Any suggestions how can i implement this ?
Or is ther any predefined utility class for conversion of the output to HashMap again ?
For me a proper way would be to use a JSON parser like Jackson since the way a HashMap is serialized is not meant to be parsed after such that if you use specific characters like = or , they won't be escaped which makes it unparsable.
How to serialize a Map with Jackson?
ObjectMapper mapper = new ObjectMapper();
String result = mapper.writeValueAsString(myMap);
How to deserialize a String to get a Map with Jackson?
ObjectMapper mapper = new ObjectMapper();
Map map = mapper.readValue(contentToParse, Map.class);
You can try to use this:
String[] tk = mystring.split(" |=");
Map<String, String> map = new HashMap<>();
for (int i=0; i < tk.length-1; i++)
{
map.put(tk[i], tk[i]);
}
return map;
If you want to replicate the Java code filling the map, you may use something like this:
StringBuilder sb = new StringBuilder("Map<String, String> test = new HashMap<>();");
for(Map.Entry<?, ?> entry : test.entrySet())
{
sb.append("\ntest.put(\"");
sb.append(entry.getKey());
sb.append("\", \"");
sb.append(entry.getValue());
sb.append("\");");
}
String string = sb.toString();
System.out.println(string);
But I agree with the comments, that in many applications a format such as JSON is more appropriate to serialize a map.
Note that the above solution does not escape strings, it only works if the strings don't contain characters like " or \n. If you need to handle these cases it will become more complicated.
You could try the following:
String out = test.toString();
Map<String, String> newMap = new HashMap();
// remove the first and last "{", "}"
out = out.subString(1,out.size()-1)
String[] newOut = out.split(", ");
for (int i=0; i<newOut.length;i++){
// keyValue is size of 2. cell 0 is key, cell 1 is value
String[] keyValue = newOut.split("=");
newMap.put(keyValue[0], keyValue[1]);
}
I haven't tested the code in java i just wrote from my mind. I hope it will work

Parse URL with java

I am trying to create a simple REST web-server. The actual URL looks like this
http://localhost:8080/Server/files/file?id=34?firstname=alex?lastname=ozouf?age=33?firstname=kevin?lastname=gerfild?age=27
The first ID is the ID of the requested file,the number of person in the parameter is not know in advance. I want to group this person in a collection/map.
It's not mandatory for the URL to be structured in this way. I could also use this URL if it could make it easier
http://localhost:8080/Server/files/file?id=34?firstname1=alex?lastname1=ozouf?age1=33?firstname2=kevin?lastname2=gerfild?age2=27
I tried to adapt these codes but as a newbie it I got really confused.
This is my code
System.out.println(query);
final Map<String, List<String>> query_pairs = new LinkedHashMap<String, List<String>>();
final String[] pairs = query.split("&");
for (String pair : pairs) {
final int idx = pair.indexOf("=");
final String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), "UTF-8") : pair;
if (!query_pairs.containsKey(key)) {
query_pairs.put(key, new LinkedList<String>());
}
final String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : null;
query_pairs.get(key).add(value);
System.out.println(query_pairs);
And this is the output I got
{id=[23?firstname1=alex]}
{id=[23?firstname1=alex], lastname1=[ozouf]}
{id=[23?firstname1=alex], lastname1=[ozouf], age1=[23?firstname=kevin]}
{id=[23?firstname1=alex], lastname1=[ozouf], age1=[23?firstname=kevin], lastname=[gefild?age=22]}
You have the wrong query string "&" is the parameter separator.
http://localhost:8080/Server/files/file?id=34&firstname=alex&lastname=ozouf&age=33&firstname=kevin&lastname=gerfild&age=27
Also I see that you are trying to have two records at the same time in the URL that's impossible to have to objects records in the query string. For this use the POST method and it body.

Get parameter after "#" from url java

I have a redirect uri of the form https://stackexchange.com/oauth/login_success#access_token=token&expires=5678. I am trying to get the acces token from this url. tried following methods
uri.getQueryParameter("access_token"); //will return null since it is not a query param
uri.getFragment(); //will return "access_token=token&expires=5678" so i need to seperate it again.
Any direct methods? Pls help
Some one might find this helpful
String queryAfterFragment = uri.getFragment();
String dummy_url = "http://localhost?" + queryAfterFragment;
Uri dummy_uri = Uri.parse(dummy_url);
String access_token = dummy_uri.getQueryParameter("access_token");
Works like a charm and easy to use, thank me later :-)
Simple and elegant solution which can get the values which you want:
public static Map<String, String> parseUrlFragment (String url) {
Map<String, String> output = new LinkedHashMap<> ();
String[] keys = url.split ("&");
for (String key : keys) {
String[] values = key.split ("=");
output.put (values[0], (values.length > 1 ? values[1] : ""));
}
return output;
}
It's using LinkedHashMap to represent values, so it's output:
Map<String, String> data = parseUrlFragment (uri.getFragment ());
data.get ("access_token") // token
data.get ("expires") // 5678
You can try in this way
String str = "https://stackexchange.com/oauth/
login_success#access_token=token&expires=5678";
int indexOfHash = str.indexOf("#");
// now you can substring from this
String subStr = str.substring(indexOfHash+1, str.length());
System.out.println(subStr);
// now you can substring from &
String sStr=subStr.substring(0,subStr.indexOf("&"));
System.out.println(sStr);
// now you can get token
String[] arr=sStr.split("=");
System.out.println(arr[0]);
System.out.println(arr[1]);
Out put
access_token=token&expires=5678
access_token=token
access_token
token
You could use the String method split(String) with Regex
str.split("#|&|=")
this splits the string by the passed 3 chars and you get an array with all the splitted parts.
String s =
"https://stackexchange.com/oauth/login_success#access_token=token&expires=5678";
final String[] split = s.split("#|&|=");
for (String s1 : split) {
System.out.println(s1);
}
Output:
https://stackexchange.com/oauth/login_success
access_token
token
expires
5678

Parsing query strings on Android

Java EE has ServletRequest.getParameterValues().
On non-EE platforms, URL.getQuery() simply returns a string.
What's the normal way to properly parse the query string in a URL when not on Java EE?
It is popular in the answers to try and make your own parser. This is very interesting and exciting micro-coding project, but I cannot say that it is a good idea.
The code snippets below are generally flawed or broken. Breaking them is an interesting exercise for the reader. And to the hackers attacking the websites that use them.
Parsing query strings is a well defined problem but reading the spec and understanding the nuances is non-trivial. It is far better to let some platform library coder do the hard work, and do the fixing, for you!
On Android:
import android.net.Uri;
[...]
Uri uri=Uri.parse(url_string);
uri.getQueryParameter("para1");
Since Android M things have got more complicated. The answer of android.net.URI.getQueryParameter() has a bug which breaks spaces before JellyBean.
Apache URLEncodedUtils.parse() worked, but was deprecated in L, and removed in M.
So the best answer now is UrlQuerySanitizer. This has existed since API level 1 and still exists. It also makes you think about the tricky issues like how do you handle special characters, or repeated values.
The simplest code is
UrlQuerySanitizer.ValueSanitizer sanitizer = UrlQuerySanitizer.getAllButNullLegal();
// remember to decide if you want the first or last parameter with the same name
// If you want the first call setPreferFirstRepeatedParameter(true);
sanitizer.parseUrl(url);
String value = sanitizer.getValue("paramName");
If you are happy with the default parsing behavior you can do:
new UrlQuerySanitizer(url).getValue("paramName")
but you should make sure you understand what the default parsing behavor is, as it might not be what you want.
On Android, the Apache libraries provide a Query parser:
http://developer.android.com/reference/org/apache/http/client/utils/URLEncodedUtils.html and http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/utils/URLEncodedUtils.html
public static Map<String, List<String>> getUrlParameters(String url)
throws UnsupportedEncodingException {
Map<String, List<String>> params = new HashMap<String, List<String>>();
String[] urlParts = url.split("\\?");
if (urlParts.length > 1) {
String query = urlParts[1];
for (String param : query.split("&")) {
String pair[] = param.split("=", 2);
String key = URLDecoder.decode(pair[0], "UTF-8");
String value = "";
if (pair.length > 1) {
value = URLDecoder.decode(pair[1], "UTF-8");
}
List<String> values = params.get(key);
if (values == null) {
values = new ArrayList<String>();
params.put(key, values);
}
values.add(value);
}
}
return params;
}
If you have jetty (server or client) libs on your classpath you can use the jetty util classes (see javadoc), e.g.:
import org.eclipse.jetty.util.*;
URL url = new URL("www.example.com/index.php?foo=bar&bla=blub");
MultiMap<String> params = new MultiMap<String>();
UrlEncoded.decodeTo(url.getQuery(), params, "UTF-8");
assert params.getString("foo").equals("bar");
assert params.getString("bla").equals("blub");
If you're using Spring 3.1 or greater (yikes, was hoping that support went back further), you can use the UriComponents and UriComponentsBuilder:
UriComponents components = UriComponentsBuilder.fromUri(uri).build();
List<String> myParam = components.getQueryParams().get("myParam");
components.getQueryParams() returns a MultiValueMap<String, String>
Here's some more documentation.
I have methods to achieve this:
1):
public static String getQueryString(String url, String tag) {
String[] params = url.split("&");
Map<String, String> map = new HashMap<String, String>();
for (String param : params) {
String name = param.split("=")[0];
String value = param.split("=")[1];
map.put(name, value);
}
Set<String> keys = map.keySet();
for (String key : keys) {
if(key.equals(tag)){
return map.get(key);
}
System.out.println("Name=" + key);
System.out.println("Value=" + map.get(key));
}
return "";
}
2) and the easiest way to do this Using Uri class:
public static String getQueryString(String url, String tag) {
try {
Uri uri=Uri.parse(url);
return uri.getQueryParameter(tag);
}catch(Exception e){
Log.e(TAG,"getQueryString() " + e.getMessage());
}
return "";
}
and this is an example of how to use either of two methods:
String url = "http://www.jorgesys.com/advertisements/publicidadmobile.htm?position=x46&site=reform&awidth=800&aheight=120";
String tagValue = getQueryString(url,"awidth");
the value of tagValue is 800
For a servlet or a JSP page you can get querystring key/value pairs by using request.getParameter("paramname")
String name = request.getParameter("name");
There are other ways of doing it but that's the way I do it in all the servlets and jsp pages that I create.
On Android, I tried using #diyism answer but I encountered the space character issue raised by #rpetrich, for example:
I fill out a form where username = "us+us" and password = "pw pw" causing a URL string to look like:
http://somewhere?username=us%2Bus&password=pw+pw
However, #diyism code returns "us+us" and "pw+pw", i.e. it doesn't detect the space character. If the URL was rewritten with %20 the space character gets identified:
http://somewhere?username=us%2Bus&password=pw%20pw
This leads to the following fix:
Uri uri = Uri.parse(url_string.replace("+", "%20"));
uri.getQueryParameter("para1");
Parsing the query string is a bit more complicated than it seems, depending on how forgiving you want to be.
First, the query string is ascii bytes. You read in these bytes one at a time and convert them to characters. If the character is ? or & then it signals the start of a parameter name. If the character is = then it signals the start of a paramter value. If the character is % then it signals the start of an encoded byte. Here is where it gets tricky.
When you read in a % char you have to read the next two bytes and interpret them as hex digits. That means the next two bytes will be 0-9, a-f or A-F. Glue these two hex digits together to get your byte value. But remember, bytes are not characters. You have to know what encoding was used to encode the characters. The character é does not encode the same in UTF-8 as it does in ISO-8859-1. In general it's impossible to know what encoding was used for a given character set. I always use UTF-8 because my web site is configured to always serve everything using UTF-8 but in practice you can't be certain. Some user-agents will tell you the character encoding in the request; you can try to read that if you have a full HTTP request. If you just have a url in isolation, good luck.
Anyway, assuming you are using UTF-8 or some other multi-byte character encoding, now that you've decoded one encoded byte you have to set it aside until you capture the next byte. You need all the encoded bytes that are together because you can't url-decode properly one byte at a time. Set aside all the bytes that are together then decode them all at once to reconstruct your character.
Plus it gets more fun if you want to be lenient and account for user-agents that mangle urls. For example, some webmail clients double-encode things. Or double up the ?&= chars (for example: http://yoursite.com/blah??p1==v1&&p2==v2). If you want to try to gracefully deal with this, you will need to add more logic to your parser.
On Android its simple as the code below:
UrlQuerySanitizer sanitzer = new UrlQuerySanitizer(url);
String value = sanitzer.getValue("your_get_parameter");
Also if you don't want to register each expected query key use:
sanitzer.setAllowUnregisteredParamaters(true)
Before calling:
sanitzer.parseUrl(yourUrl)
On Android, you can use the Uri.parse static method of the android.net.Uri class to do the heavy lifting. If you're doing anything with URIs and Intents you'll want to use it anyways.
Just for reference, this is what I've ended up with (based on URLEncodedUtils, and returning a Map).
Features:
it accepts the query string part of the url (you can use request.getQueryString())
an empty query string will produce an empty Map
a parameter without a value (?test) will be mapped to an empty List<String>
Code:
public static Map<String, List<String>> getParameterMapOfLists(String queryString) {
Map<String, List<String>> mapOfLists = new HashMap<String, List<String>>();
if (queryString == null || queryString.length() == 0) {
return mapOfLists;
}
List<NameValuePair> list = URLEncodedUtils.parse(URI.create("http://localhost/?" + queryString), "UTF-8");
for (NameValuePair pair : list) {
List<String> values = mapOfLists.get(pair.getName());
if (values == null) {
values = new ArrayList<String>();
mapOfLists.put(pair.getName(), values);
}
if (pair.getValue() != null) {
values.add(pair.getValue());
}
}
return mapOfLists;
}
A compatibility helper (values are stored in a String array just as in ServletRequest.getParameterMap()):
public static Map<String, String[]> getParameterMap(String queryString) {
Map<String, List<String>> mapOfLists = getParameterMapOfLists(queryString);
Map<String, String[]> mapOfArrays = new HashMap<String, String[]>();
for (String key : mapOfLists.keySet()) {
mapOfArrays.put(key, mapOfLists.get(key).toArray(new String[] {}));
}
return mapOfArrays;
}
This works for me..
I'm not sure why every one was after a Map, List>
All I needed was a simple name value Map.
To keep things simple I used the build in URI.getQuery();
public static Map<String, String> getUrlParameters(URI uri)
throws UnsupportedEncodingException {
Map<String, String> params = new HashMap<String, String>();
for (String param : uri.getQuery().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");
}
params.put(new String(key), new String(value));
}
return params;
}
Guava's Multimap is better suited for this. Here is a short clean version:
Multimap<String, String> getUrlParameters(String url) {
try {
Multimap<String, String> ret = ArrayListMultimap.create();
for (NameValuePair param : URLEncodedUtils.parse(new URI(url), "UTF-8")) {
ret.put(param.getName(), param.getValue());
}
return ret;
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
Origanally answered here
On Android, there is Uri class in package android.net . Note that Uri is part of android.net, while URI is part of java.net .
Uri class has many functions to extract query key-value pairs.
Following function returns key-value pairs in the form of HashMap.
In Java:
Map<String, String> getQueryKeyValueMap(Uri uri){
HashMap<String, String> keyValueMap = new HashMap();
String key;
String value;
Set<String> keyNamesList = uri.getQueryParameterNames();
Iterator iterator = keyNamesList.iterator();
while (iterator.hasNext()){
key = (String) iterator.next();
value = uri.getQueryParameter(key);
keyValueMap.put(key, value);
}
return keyValueMap;
}
In Kotlin:
fun getQueryKeyValueMap(uri: Uri): HashMap<String, String> {
val keyValueMap = HashMap<String, String>()
var key: String
var value: String
val keyNamesList = uri.queryParameterNames
val iterator = keyNamesList.iterator()
while (iterator.hasNext()) {
key = iterator.next() as String
value = uri.getQueryParameter(key) as String
keyValueMap.put(key, value)
}
return keyValueMap
}
Apache AXIS2 has a self-contained implementation of QueryStringParser.java. If you are not using Axis2, just download the sourcecode and test case from here -
http://svn.apache.org/repos/asf/axis/axis2/java/core/trunk/modules/kernel/src/org/apache/axis2/transport/http/util/QueryStringParser.java
http://svn.apache.org/repos/asf/axis/axis2/java/core/trunk/modules/kernel/test/org/apache/axis2/transport/http/util/QueryStringParserTest.java
if (queryString != null)
{
final String[] arrParameters = queryString.split("&");
for (final String tempParameterString : arrParameters)
{
final String[] arrTempParameter = tempParameterString.split("=");
if (arrTempParameter.length >= 2)
{
final String parameterKey = arrTempParameter[0];
final String parameterValue = arrTempParameter[1];
//do something with the parameters
}
}
}
I don't think there is one in JRE. You can find similar functions in other packages like Apache HttpClient. If you don't use any other packages, you just have to write your own. It's not that hard. Here is what I use,
public class QueryString {
private Map<String, List<String>> parameters;
public QueryString(String qs) {
parameters = new TreeMap<String, List<String>>();
// Parse query string
String pairs[] = qs.split("&");
for (String pair : pairs) {
String name;
String value;
int pos = pair.indexOf('=');
// for "n=", the value is "", for "n", the value is null
if (pos == -1) {
name = pair;
value = null;
} else {
try {
name = URLDecoder.decode(pair.substring(0, pos), "UTF-8");
value = URLDecoder.decode(pair.substring(pos+1, pair.length()), "UTF-8");
} catch (UnsupportedEncodingException e) {
// Not really possible, throw unchecked
throw new IllegalStateException("No UTF-8");
}
}
List<String> list = parameters.get(name);
if (list == null) {
list = new ArrayList<String>();
parameters.put(name, list);
}
list.add(value);
}
}
public String getParameter(String name) {
List<String> values = parameters.get(name);
if (values == null)
return null;
if (values.size() == 0)
return "";
return values.get(0);
}
public String[] getParameterValues(String name) {
List<String> values = parameters.get(name);
if (values == null)
return null;
return (String[])values.toArray(new String[values.size()]);
}
public Enumeration<String> getParameterNames() {
return Collections.enumeration(parameters.keySet());
}
public Map<String, String[]> getParameterMap() {
Map<String, String[]> map = new TreeMap<String, String[]>();
for (Map.Entry<String, List<String>> entry : parameters.entrySet()) {
List<String> list = entry.getValue();
String[] values;
if (list == null)
values = null;
else
values = (String[]) list.toArray(new String[list.size()]);
map.put(entry.getKey(), values);
}
return map;
}
}
public static Map <String, String> parseQueryString (final URL url)
throws UnsupportedEncodingException
{
final Map <String, String> qps = new TreeMap <String, String> ();
final StringTokenizer pairs = new StringTokenizer (url.getQuery (), "&");
while (pairs.hasMoreTokens ())
{
final String pair = pairs.nextToken ();
final StringTokenizer parts = new StringTokenizer (pair, "=");
final String name = URLDecoder.decode (parts.nextToken (), "ISO-8859-1");
final String value = URLDecoder.decode (parts.nextToken (), "ISO-8859-1");
qps.put (name, value);
}
return qps;
}
Use Apache HttpComponents and wire it up with some collection code to access params by value: http://www.joelgerard.com/2012/09/14/parsing-query-strings-in-java-and-accessing-values-by-key/
using Guava:
Multimap<String,String> parseQueryString(String queryString, String encoding) {
LinkedListMultimap<String, String> result = LinkedListMultimap.create();
for(String entry : Splitter.on("&").omitEmptyStrings().split(queryString)) {
String pair [] = entry.split("=", 2);
try {
result.put(URLDecoder.decode(pair[0], encoding), pair.length == 2 ? URLDecoder.decode(pair[1], encoding) : null);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
return result;
}
Answering here because this is a popular thread. This is a clean solution in Kotlin that uses the recommended UrlQuerySanitizer api. See the official documentation. I have added a string builder to concatenate and display the params.
var myURL: String? = null
// if the url is sent from a different activity where you set it to a value
if (intent.hasExtra("my_value")) {
myURL = intent.extras.getString("my_value")
} else {
myURL = intent.dataString
}
val sanitizer = UrlQuerySanitizer(myURL)
// We don't want to manually define every expected query *key*, so we set this to true
sanitizer.allowUnregisteredParamaters = true
val parameterNamesToValues: List<UrlQuerySanitizer.ParameterValuePair> = sanitizer.parameterList
val parameterIterator: Iterator<UrlQuerySanitizer.ParameterValuePair> = parameterNamesToValues.iterator()
// Helper simply so we can display all values on screen
val stringBuilder = StringBuilder()
while (parameterIterator.hasNext()) {
val parameterValuePair: UrlQuerySanitizer.ParameterValuePair = parameterIterator.next()
val parameterName: String = parameterValuePair.mParameter
val parameterValue: String = parameterValuePair.mValue
// Append string to display all key value pairs
stringBuilder.append("Key: $parameterName\nValue: $parameterValue\n\n")
}
// Set a textView's text to display the string
val paramListString = stringBuilder.toString()
val textView: TextView = findViewById(R.id.activity_title) as TextView
textView.text = "Paramlist is \n\n$paramListString"
// to check if the url has specific keys
if (sanitizer.hasParameter("type")) {
val type = sanitizer.getValue("type")
println("sanitizer has type param $type")
}
this method takes the uri and return map of par name and par value
public static Map<String, String> getQueryMap(String uri) {
String queryParms[] = uri.split("\\?");
Map<String, String> map = new HashMap<>();//
if (queryParms == null || queryParms.length == 0) return map;
String[] params = queryParms[1].split("&");
for (String param : params) {
String name = param.split("=")[0];
String value = param.split("=")[1];
map.put(name, value);
}
return map;
}
You say "Java" but "not Java EE". Do you mean you are using JSP and/or servlets but not a full Java EE stack? If that's the case, then you should still have request.getParameter() available to you.
If you mean you are writing Java but you are not writing JSPs nor servlets, or that you're just using Java as your reference point but you're on some other platform that doesn't have built-in parameter parsing ... Wow, that just sounds like an unlikely question, but if so, the principle would be:
xparm=0
word=""
loop
get next char
if no char
exit loop
if char=='='
param_name[xparm]=word
word=""
else if char=='&'
param_value[xparm]=word
word=""
xparm=xparm+1
else if char=='%'
read next two chars
word=word+interpret the chars as hex digits to make a byte
else
word=word+char
(I could write Java code but that would be pointless, because if you have Java available, you can just use request.getParameters.)

Categories