Decode given URL Query String to map. - Java Network

Java examples for Network:URL

Description

Decode given URL Query String to map.

Demo Code


//package com.java2s;

import java.io.UnsupportedEncodingException;

import java.net.URLDecoder;

import java.util.HashMap;
import java.util.Map;

public class Main {


    /**/*from  w w w .java2s .  c  o  m*/
     * Decode given String to map. For example for input: accessToken=123456&expires=20071458 it returns map with two keys
     * "accessToken" and "expires" and their corresponding values
     *
     * @param encodedData
     * @return map with output data
     */
    public static Map<String, String> formUrlDecode(String encodedData) {
        Map<String, String> params = new HashMap<String, String>();
        String[] elements = encodedData.split("&");
        for (String element : elements) {
            String[] pair = element.split("=");
            if (pair.length == 2) {
                String paramName = pair[0];
                String paramValue;
                try {
                    paramValue = URLDecoder.decode(pair[1], "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
                params.put(paramName, paramValue);
            } else {
                throw new RuntimeException(
                        "Unexpected name-value pair in response: "
                                + element);
            }
        }
        return params;
    }
}

Related Tutorials