HTTP and Java

URL

The class java.net.URL is designed to make it easier to handle fetching url data. You don't have to open sockets yourself



/**
 * SimpleURL.java
 */

import java.net.*;
import java.io.*;

public class SimpleURL{
    public SimpleURL (){
	
    }
    
    public static void main(String[] args){
	if (args.length != 1) {
	    System.err.println("Usage: java SimpleURL url");
	    System.exit(1);
	}

	URL url = null;
	try {
	    url = new URL(args[0]);
	} catch(MalformedURLException e) {
	    e.printStackTrace();
	    System.exit(1);
	}
	Object content = null;
	try {
	    content = url.getContent();
	} catch(IOException e) {
	    e.printStackTrace();
	    System.exit(2);
	}
	// The content is actually a subclass of InputStream
	BufferedReader reader = null;
	reader = new BufferedReader(new InputStreamReader((InputStream) content));
	String line;
	try {
	    while ((line = reader.readLine()) != null) {
		System.out.println(line);
	    }
	} catch (IOException e) {
	    e.printStackTrace();
	    System.exit(3);
	}
    }
} // SimpleURL

URLConnection

If you want to get extra information about the url, the class URLConnection can be used


/**
 * URLInfo.java
 */
import java.net.*;
import java.io.*;

public class URLInfo{
    public URLInfo (){
	
    }
    
    public static void main(String[] args){
	URL url = null;
	try {
	    url = new URL("http://localhost/ecommerce/cgiapps.gif");
	} catch(MalformedURLException e) {
	    e.printStackTrace();
	    System.exit(1);
	}
	URLConnection connection = null;
	InputStream str = null;
	try {
	    connection = url.openConnection();
	    connection.connect();
	} catch(IOException e) {
	    e.printStackTrace();
	    System.exit(1);
	}
	System.out.println("Type " + connection.getContentType());
	System.out.println("Length " + connection.getContentLength());

    }
} // URLInfo

Forms

HTTP connections write information from client to HTTP server and read the reply. This can be used to fetch static URLs (as above). It can also be used to post form data and read the reply. The URLConnection can be used for this


/**
 * CGI.java
 */
import java.net.*;
import java.io.*;

public class CGI{
    public CGI (){
	
    }
    
    public static void main(String[] args){
	URL url = null;
	try {
	    url = new URL("http://localhost/cgi-bin/test-cgi");
	} catch(MalformedURLException e) {
	    e.printStackTrace();
	    System.exit(1);
	}
	URLConnection connection = null;
	InputStream istr = null;
	OutputStream ostr = null;
	try {
	    connection = url.openConnection();
	    // doOutput must be set before connecting
	    connection.setDoOutput(true);
	    connection.connect();
	    ostr = connection.getOutputStream();
	} catch(IOException e) {
	    e.printStackTrace();
	    System.exit(1);
	}

	DataOutputStream writer = new DataOutputStream(ostr);
	try {
	    writer.writeBytes("name=jan\n");
	    writer.flush();
	    writer.close();
	} catch(IOException e) {
	    e.printStackTrace();
	    System.exit(1);
	}

	// After writing is over, we can read the reply
	try {
	    istr = connection.getInputStream();
	} catch(IOException e) {
	    e.printStackTrace();
	    System.exit(1);
	}
	BufferedReader reader = new BufferedReader(new InputStreamReader(istr));
	String line;
        try {
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(3);
        }

    }
} // CGI

Authorization

Proxies

Proxy Authorization

Displaying URLs

Some classes that are useful on the client side for displaying documents

HTTP server

Server-side processing - Servlets

Servlet template


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SomeServlet extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
      
    // Use "request" to read incoming HTTP headers (e.g. cookies)
    // and HTML form data (e.g. data the user entered and submitted)
    
    // Use "response" to specify the HTTP response line and headers
    // (e.g. specifying the content type, setting cookies).
    
    PrintWriter out = response.getWriter();
    // Use "out" to send content to browser
  }
}

HelloWorld servlet (plain text)


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    out.println("Hello World");
  }
}

HelloWorld servlet (HTML)


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWWW extends HttpServlet {
    public void doGet(HttpServletRequest request,
		      HttpServletResponse response)
		throws ServletException, IOException {
	response.setContentType("text/html");
	PrintWriter out = response.getWriter();
	String docType = 
		"<!DOCTYPE HTML PUBLIC \"-//W3C/DTD HTML 4.0 " +
		"Transitional//EN\"\n";
	out.println(docType +
		    "<HTML>\n" +
		    "<head><title>Hello WWW</title></head>\n" +
		    "<body>\n" +
		    "<h1> Hello WWW</h1>" +
		    "</body></html>");
    }
}

Form parameters


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

public class ThreeParams extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Reading Three Request Parameters";
    out.println(ServletUtilities.headWithTitle(title) +
                "&lt;BODY&gt;\n" +
                "&lt;H1 ALIGN=CENTER&gt;" + title + "&lt;/H1&gt;\n" +
                "&lt;UL&gt;\n" +
                "  &lt;LI&gt;param1: "
                + request.getParameter("param1") + "\n" +
                "  &lt;LI&gt;param2: "
                + request.getParameter("param2") + "\n" +
                "  &lt;LI&gt;param3: "
                + request.getParameter("param3") + "\n" +
                "&lt;/UL&gt;\n" +
                "&lt;/BODY&gt;&lt;/HTML&gt;");
  }

  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
    doGet(request, response);
  }
}

Cookies

Session tracking


Jan Newmarch (http://jan.newmarch.name)
jan@newmarch.name
Last modified: Mon Aug 21 22:41:42 EST 2006
Copyright ©Jan Newmarch
Copyright © Jan Newmarch, Monash University, 2007
Creative Commons License This work is licensed under a Creative Commons License
The moral right of Jan Newmarch to be identified as the author of this page has been asserted.