The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.net  [27 examples] > Encodings  [2 examples]

e157. 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) {
    }

 Related Examples
e156. Converting Between a Byte Array and Base64

See also: Datagram    HTTP    Hostnames and IP Addresses    Multicast    Sockets    URLs   


© 2002 Addison-Wesley.