Build query string for URL in Java

Description

The following code shows how to build query string for URL.

Example


     /*from ww w  .  j  av  a  2 s  .c om*/

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

public class Main {

  public static void main(String[] args) {
    QueryString qs = new QueryString("pg", "q");
    qs.add("kl", "XX");
    qs.add("stype", "stext");
    qs.add("q", "+\"Java Programming\"");
    String url = "http://www.java.com/query?" + qs;
    System.out.println(url);
  }
}

class QueryString {

  private String query = "";

  public QueryString(String name, String value) {
    encode(name, value);
  }

  public void add(String name, String value) {
    query += "&";
    encode(name, value);
  }

  private void encode(String name, String value) {
    try {
      query +=URLEncoder.encode(name, "UTF-8");
      query += "=";
      query += URLEncoder.encode(value, "UTF-8");
    } catch (UnsupportedEncodingException ex) {
      throw new RuntimeException("Broken VM does not support UTF-8");
    }
  }

  public String getQuery() {
    return query;
  }

  public String toString() {
    return getQuery();
  }

}

The code above generates the following result.





















Home »
  Java Tutorial »
    Network »




NetworkInterface
URI
URL
HTTP
HTTP Read
IP
Socket
UDP
URL Encode