Java URL Query Parse parse(String query, String encoding)

Here you can find the source of parse(String query, String encoding)

Description

parse

License

Open Source License

Declaration

private static Map<String, String> parse(String query, String encoding) 

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;
import java.util.Scanner;

public class Main {
    private static final String PARAMETER_SEPARATOR = "&";
    private static final String NAME_VALUE_SEPARATOR = "=";
    private static final String DEFAULT_CHARSET = "ISO-8859-1";

    private static Map<String, String> parse(String query, String encoding) {
        Map<String, String> result = new HashMap<String, String>();

        Scanner scanner = new Scanner(query);
        scanner.useDelimiter(PARAMETER_SEPARATOR);
        while (scanner.hasNext()) {
            String[] nameValue = scanner.next().split(NAME_VALUE_SEPARATOR);
            if (nameValue.length <= 0 || nameValue.length > 2) {
                continue;
            }//from  www . j a v a  2 s  .c  o  m

            String name = decode(nameValue[0], encoding);
            String value = null;
            if (nameValue.length == 2) {
                value = decode(nameValue[1], encoding);
            }
            result.put(name, value);
        }
        return result;
    }

    private static String decode(final String content, final String encoding) {
        try {
            return URLDecoder.decode(content, encoding != null ? encoding : DEFAULT_CHARSET);
        } catch (UnsupportedEncodingException e) {
            throw new IllegalArgumentException(e);
        }
    }
}

Related

  1. parseInstructions(final String query)
  2. parseParameters( Optional queryString)
  3. parseParameters(String query)
  4. parseQuery(String query)