Java URI to Parameter extractUriParameters(String uriString)

Here you can find the source of extractUriParameters(String uriString)

Description

Extracts the URI parameters from the given URI string into a Map.

License

Open Source License

Parameter

Parameter Description
uriString URI string to decode

Return

map of URI parameters

Declaration

public static Map extractUriParameters(String uriString) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import java.util.HashMap;

import java.util.Map;

public class Main {
    public static final String QUERY_CHAR = "?";
    public static final String ANCHOR_CHAR = "#";
    public static final String PARAM_EQUALS = "=";
    /**//from   w  w  w. j av  a2  s . co m
     * UTF-8 encode constants.
     */
    public static final String UTF_8_ENCODING = "UTF-8";

    /**
     * Extracts the URI parameters from the given URI string into a Map.
     * 
     * @param uriString
     *            URI string to decode
     * @return map of URI parameters
     */
    public static Map extractUriParameters(String uriString) {
        Map params = new HashMap();
        if (uriString != null) {
            int anchorPosition = uriString.indexOf(ANCHOR_CHAR);
            if (anchorPosition >= 0) {
                uriString = uriString.substring(0, anchorPosition);
            }

            int queryPosition = uriString.indexOf(QUERY_CHAR);
            if (queryPosition >= 0) {
                uriString = uriString.substring(queryPosition + 1);
            }

            String[] uriParts = uriString.split("\\&"); //$NON-NLS-1$
            for (int i = 0; i < uriParts.length; i++) {
                String param = uriParts[i];
                String[] paramParts = param.split(PARAM_EQUALS);
                if (paramParts.length > 0) {
                    String paramName = urlParamValueDecode(paramParts[0]);
                    String paramValue = null;
                    if (paramParts.length > 1) {
                        paramValue = urlParamValueDecode(paramParts[1]);
                    }

                    if (paramName != null && paramName.length() > 0) {
                        params.put(paramName, paramValue);
                    }
                }
            }
        }
        return params;
    }

    /**
     * Decodes the url parameter value
     * 
     * @param s
     *            string to decode
     * @return
     */
    public static String urlParamValueDecode(String s) {
        if (s != null) {
            try {
                return URLDecoder.decode(s, UTF_8_ENCODING);
            } catch (UnsupportedEncodingException e) {
            }
        }
        return s;
    }
}

Related

  1. extractUriParameters(URI uri)
  2. getKey(String uri)
  3. getKey(URI uri)
  4. getParameters(URI uri)