Parse URL QueryString by UTF-8 encoding to Map - Java java.net

Java examples for java.net:URL Query

Description

Parse URL QueryString by UTF-8 encoding to Map

Demo Code

//package com.java2s;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import java.util.LinkedHashMap;

public class Main {
    public static void main(String[] argv) {
        String queryString = "&asdf=java2s.com;";
        System.out.println(parse(queryString));
    }/*  w ww .  j a v  a  2  s.c  o m*/

    private static final String DEFAULT_ENCODING = "UTF-8";

    /**
     * Parse URL QueryString by UTF-8 encoding to Map
     * 
     * @param queryString
     *          Query String
     * @return Map
     */
    public static LinkedHashMap<String, String> parse(String queryString) {
        return parse(queryString, DEFAULT_ENCODING);
    }

    /**
     * Parse URL QueryString to Map<String,String>
     * 
     * @param queryString
     *          QueryString
     * @param encoding
     *          URL Encoding
     * @return If the queryString contains multiple parameters with a same name, first returned
     */
    public static LinkedHashMap<String, String> parse(String queryString,
            String encoding) {

        LinkedHashMap<String, String> params = new LinkedHashMap<>();

        if (queryString == null) {
            return params;
        }

        queryString = queryString.trim();

        if (queryString.startsWith("?"))
            queryString = queryString.substring(1);

        if (queryString.length() == 0)
            return params;

        for (String s : queryString.split("&")) {

            String k, v;

            if (s.contains("=")) {

                String[] pr = s.split("=", 2);

                try {
                    k = URLDecoder.decode(pr[0].trim(), encoding);
                    v = URLDecoder.decode(pr[1].trim(), encoding);
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }

            } else {

                try {
                    k = URLDecoder.decode(s.trim(), encoding);
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }

                v = "";
            }

            if (k.length() > 0 && !params.containsKey(k)) {
                params.put(k, v);
            }
        }

        return params;
    }
}

Related Tutorials