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






Call a servlet from a Java command line application

       
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.URL;
import java.net.URLConnection;

public class CounterApp {

  public static void main(String args[])throws Exception {
    String sessionCookie = null;
    URL url = new java.net.URL("http://127.0.0.1/yourServlet");
    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);
      }
    }

    System.out.println(count);
  }

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

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

   
    
    
    
    
    
  








Related examples in the same category

1.Demonstrate URLConnection.
2.A CGI POST Example
3.Http authentication header
4.URLConnection.setRequestProperty
5.File size from URL
6.Sending a POST Request Using a URL
7.Check if a file was modified on the server
8.Getting Text from a URL
9.Getting an Image from a URL
10.Sending a POST Request with Parameters From a Java Class
11.Downloading a web page using URL and URLConnection classes
12.Get response header from HTTP request
13.Read / download webpage content
14.Read a GIF or CLASS from an URL save it locally
15.Zip URLConnection
16.Zip URLStream Handler
17.Http Parser
18.Http Constants
19.Get URLConnection Expiration
20.Locating files by path or URL
21.Download from URL
22.This program demonstrates how to use the URLConnection class for a POST request.
23.Connects to an URL and displays the response header data and the first 10 lines of the requested data.Connects to an URL and displays the response header data and the first 10 lines of the requested data.
24.Load content from URL to string