Converting x-www-form-urlencoded Data - Java Network

Java examples for Network:URL

Description

Converting x-www-form-urlencoded Data

name1=value1&name2=value2

Demo Code


import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class Main {
  public static void main(String[] args) {
    try {//  w ww .j a v  a 2s .co  m
      // 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 Tutorials