본문 바로가기

Servlet/URLEncoder, Decoder

Converting x-www-form-urlencoded Data

Name/value pairs that are formatted using the x-www-form-urlencoded specification appear as:
    name1=value1&name2=value2
where nameN and valueN must be escaped. For example, a+b will appear as a%2Bb when escaped. The URLEncoder and URLDecoder classes are used to escape the names and values.
    try {
        // Construct a x-www-form-urlencoded string
        String line = URLEncoder.encode("name1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
        line += "&" + URLEncoder.encode("name2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
    
        // Parse a x-www-form-urlencoded string
        String[] pairs = line.split("\\&");
        for (int i=0; i<pairs.length; i++) {
            String[] fields = pairs[i].split("=");
            String name = URLDecoder.decode(fields[0], "UTF-8");
            String value = URLDecoder.decode(fields[1], "UTF-8");
        }
    } catch (UnsupportedEncodingException e) {
    }