dd619
dd619

Reputation: 6170

How to get HashMap of all variables from url

I just want to know how can we retrieve all variables from URL with its value in android(Java).

E.g if I have URL as below,
http://www.sample.com/json/just_in.asp?variable1=value1&variable2=value2

then want to retrieve variable1 and variable2 with its value and store it in hashmap where
key=variable name(variable1)

and value=variable value(value1)

Upvotes: 0

Views: 5595

Answers (4)

Rajitha Bhanuka
Rajitha Bhanuka

Reputation: 842

In my case, I wrote

private static final String SYMBOL_EQUAL = "=";
private static final String SYMBOL_COMMA = ",";
private static final String SYMBOL_AND = "&";

   public static HashMap<String, String> getParamList(String encodedUrl) throws IOException {

    final HashMap<String, String> map = new HashMap<String, String>();
    final String url = URLDecoder.decode(encodedUrl, StandardCharsets.UTF_8.name());
    final String[] params = url.split(SYMBOL_AND);

    try {
        for (final String param : params) {
            final String name = param.split(SYMBOL_EQUAL)[0];
            final String value = param.split(SYMBOL_EQUAL)[1];
            map.put(name, value);
        }
    } catch (final Exception e) {
        LOGGER.error(e.getMessage());
    }
    return map;
}

Upvotes: 0

Nargis
Nargis

Reputation: 4787

Use this simple code

 final String[] params = url.split("&");
        final Map<String, String> map = new HashMap<String, String>();
        try {
            for (final String param : params) {
                final String name = param.split("=")[0];
                final String value = param.split("=")[1];
                map.put(name, value);
            }
        } catch (final Exception e) {
            e.printStackTrace();
        }

Upvotes: 1

Ken Wolf
Ken Wolf

Reputation: 23269

Like so:

HashMap<String, String> map = new HashMap<String, String>();
try {
    String url = "http://www.sample.com/json/just_in.asp?variable1=value1&variable2=value2";
    List<NameValuePair> parameters = URLEncodedUtils.parse(new URI(url), "UTF-8");
    for (NameValuePair p : parameters) {
        map.put(p.getName(), p.getValue());
    }
} catch (URISyntaxException e) {
    e.printStackTrace();
}

map will contain key/value pairs of your parameters.

Upvotes: 3

BLaZuRE
BLaZuRE

Reputation: 2406

Create a Uri object out of your URL/string.

String myUrl = "http://www.sample.com/json/just_in.asp?variable1=value1&variable2=value2";

Uri uri = Uri.parse(myUrl);
String variable1 = uri.getQueryParameter("variable1");
String variable2 = uri.getQueryParameter("variable2");

See http://developer.android.com/reference/android/net/Uri.html for more information on the topic.

Upvotes: 2

Related Questions