Java URL Query Build getQueryParameter(String query, String key, String encoding)

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

Description

get Query Parameter

License

Open Source License

Declaration

public static String getQueryParameter(String query, String key, 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";

    public static String getQueryParameter(String query, String key) {
        return getQueryParameter(query, key, DEFAULT_CHARSET);
    }//  w  w  w.j a v  a 2s.co  m

    public static String getQueryParameter(String query, String key, String encoding) {
        Map<String, String> result = parse(query, encoding);
        if (result == null) {
            return null;
        } else {
            return result.get(key);
        }
    }

    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;
            }

            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. getQuery(URL theURL)
  2. getQueryFromURL(URL url)
  3. getQueryMap(String query)
  4. getQueryMap(String urlString)
  5. getQueryMap(URL url)
  6. getQueryParameterMap(String queryString)
  7. getQueryParameters(URL url)
  8. getQueryParameters(URL url)
  9. getQueryParameters(URL url)