Call a servlet from a Java command line application : URLConnection « Network « Java Tutorial






import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;

public class CounterApp {
  String servletURL;

  String sessionCookie = null;

  public static void main(String args[]) {
    if (args.length == 0) {
      System.out.println("\nServlet URL must be specified");
      return;
    }

    try {
      CounterApp app = new CounterApp(args[0]);
      for (int i = 1; i <= 5; i++) {
        int count = app.getCount();
        System.out.println("Pass " + i + " count=" + count);
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }

  }

  public CounterApp(String url) {
    servletURL = url;
  }

  public int getCount() throws Exception {
    java.net.URL url = new java.net.URL(servletURL);
    java.net.URLConnection con = url.openConnection();
    if (sessionCookie != null) {
      con.setRequestProperty("cookie", sessionCookie);
    }
    con.setUseCaches(false);
    con.setDoOutput(true);
    con.setDoInput(true);
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(byteOut);
    out.flush();
    byte buf[] = byteOut.toByteArray();
    con.setRequestProperty("Content-type", "application/octet-stream");
    con.setRequestProperty("Content-length", "" + buf.length);
    DataOutputStream dataOut = new DataOutputStream(con.getOutputStream());
    dataOut.write(buf);
    dataOut.flush();
    dataOut.close();
    DataInputStream in = new DataInputStream(con.getInputStream());
    int count = in.readInt();
    in.close();
    if (sessionCookie == null) {
      String cookie = con.getHeaderField("set-cookie");
      if (cookie != null) {
        sessionCookie = parseCookie(cookie);
        System.out.println("Setting session ID=" + sessionCookie);
      }
    }

    return count;
  }

  public String parseCookie(String raw) {
    String c = raw;

    if (raw != null) {
      int endIndex = raw.indexOf(";");
      if (endIndex >= 0) {
        c = raw.substring(0, endIndex);
      }
    }

    return c;
  }
}








19.3.URLConnection
19.3.1.All Headers
19.3.2.Chain the InputStream to a Reader
19.3.3.Get files updated last 24 hours
19.3.4.Encoding Aware Source Viewer
19.3.5.Call a servlet from a Java command line application
19.3.6.Read from a URL with buffered stream
19.3.7.Sending a POST Request Using a URL
19.3.8.Read a GIF or CLASS from an URL and save it locally