Java URL Parameter Builder parseGetParameters(HttpExchange exchange)

Here you can find the source of parseGetParameters(HttpExchange exchange)

Description

parse Get Parameters

License

Open Source License

Declaration

public static void parseGetParameters(HttpExchange exchange) throws UnsupportedEncodingException 

Method Source Code

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

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.sun.net.httpserver.HttpExchange;

public class Main {
    public static void parseGetParameters(HttpExchange exchange) throws UnsupportedEncodingException {

        Map<String, Object> parameters = new HashMap<String, Object>();
        URI requestedUri = exchange.getRequestURI();
        String query = requestedUri.getRawQuery();
        parseQuery(query, parameters);//  www  .  j  ava 2  s.c om
        exchange.setAttribute("parameters", parameters);
    }

    @SuppressWarnings("unchecked")
    private static void parseQuery(String query, Map<String, Object> parameters)
            throws UnsupportedEncodingException {

        if (query != null) {
            String pairs[] = query.split("[&]");

            for (String pair : pairs) {
                String param[] = pair.split("[=]");

                String key = null;
                String value = null;
                if (param.length > 0) {
                    key = URLDecoder.decode(param[0], System.getProperty("file.encoding"));
                }

                if (param.length > 1) {
                    value = URLDecoder.decode(param[1], System.getProperty("file.encoding"));
                }

                if (parameters.containsKey(key)) {
                    Object obj = parameters.get(key);
                    if (obj instanceof List<?>) {
                        List<String> values = (List<String>) obj;
                        values.add(value);
                    } else if (obj instanceof String) {
                        List<String> values = new ArrayList<String>();
                        values.add((String) obj);
                        values.add(value);
                        parameters.put(key, values);
                    }
                } else {
                    parameters.put(key, value);
                }
            }
        }
    }
}

Related

  1. mapToStr( Map map)
  2. mapToStr(Map map)
  3. mapToString(Map map)
  4. parse(final Map> parameters, final Scanner scanner, final String encoding)
  5. parse_parameters(String input)
  6. parseParameters(final String value)
  7. parseResponseParams(String body)
  8. sendGetRequest(String path, Map params, String enc)
  9. sendPostRequest(String path, Map params, String enc)