Getting Started with HTTPClient

Sending Requests

Using the HTTPClient should be quite simple. First add the import statement import HTTPClient.*; to your file(s). Request can then be sent using one of the methods Head(), Get(), Post(), etc in HTTPConnection. These methods all return an instance of HTTPResponse which has methods for accessing the response headers (getHeader(), getHeaderAsInt(), etc), various response info (getStatusCode(), getReasonLine(), etc) and the reponse data (getData() and getInputStream()). Following are some examples.

If this is in an applet you can retrieve files from your server as follows:

    try
    {
	HTTPConnection con = new HTTPConnection(this);
	HTTPResponse   rsp = con.Get("/my_file");
	if (rsp.getStatusCode() >= 300)
	{
	    System.err.println("Received Error: "+rsp.getReasonLine());
	    System.err.println(new String(rsp.getData(),0));
	}
	else
	    data = rsp.getData();

	rsp = con.Get("/another_file");
	if (rsp.getStatusCode() >= 300)
	{
	    System.err.println("Received Error: "+rsp.getReasonLine());
	    System.err.println(new String(rsp.getData(),0));
	}
	else
	    other_data = rsp.getData();
    }
    catch (IOException ioe)
    {
	System.err.println(ioe.toString());
    }
    catch (AuthTypeNotImplementedException atnie)
    {
	System.err.println("Can't handle the authorization scheme " +
			   atnie.getMessage());
    }

This will get the files "/my_file" and "/another_file" and put their contents into byte[]'s accessible via getData(). Note that you need to only create a new HTTPConnection when sending a request to a new server (different host or port); although you may create a new HTTPConnection for every request to the same server this not recommended, as various information about the server is cached after the first request (to optimize subsequent requests) and persistent connections are used whenever possible (see also Advanced Info).

To POST form data you would use something like this (assuming you have two fields called name and e-mail, whose contents are stored in the variables name and email):

    try
    {
	NVPair form_data[] = new NVPair[2];
	form_data[0] = new NVPair("name", name);
	form_data[1] = new NVPair("e-mail", email);

	HTTPConnection con = new HTTPConnection(this);
	HTTPResponse   rsp = con.Post("/cgi-bin/my_script", form_data);
	if (rsp.getStatusCode() >= 300)
	{
	    System.err.println("Received Error: "+rsp.getReasonLine());
	    System.err.println(new String(rsp.getData(),0));
	}
	else
	    stream = rsp.getInputStream();
    }
    catch (IOException ioe)
    {
	System.err.println(ioe.toString());
    }
    catch (AuthTypeNotImplementedException atnie)
    {
	System.err.println("Can't handle the authorization scheme " +
			   atnie.getMessage());
    }

Here the response data is read at leasure via an InputStream instead of all at once into a byte[].

As another example, if you have a URL you're trying to send a request to you would do something like the following:

    try
    {
	URL url = new URL("http://www.mydomain.us/test/my_file");
	HTTPConnection con = new HTTPConnection(url);
	HTTPResponse   rsp = con.Put(url.getFile(), "Hello World");
	if (rsp.getStatusCode() >= 300)
	{
	    System.err.println("Received Error: "+rsp.getReasonLine());
	    System.err.println(new String(rsp.getData(),0));
	}
	else
	    data = rsp.getData();
    }
    catch (IOException ioe)
    {
	System.err.println(ioe.toString());
    }
    catch (AuthTypeNotImplementedException atnie)
    {
	System.err.println("Can't handle the authorization scheme " +
			   atnie.getMessage());
    }

Example Applet

Here is a complete (albeit simple) Applet that uses HTTPClient to POST some data.

Authorization Handling

If the server requires authorization you will usually get a popup requesting the desired information (usually username and password), much like Netscape or other browsers do. This information will then be cached so that further accesses to the same realm will not require the information to be entered again. If you (as a programmer) know the username and password beforehand (e.g. if you are writing an applet to access a specific page on your server) you can set this information with the addAuthorization() and addBasicAuthorization() methods. The first method is more general, but since 'Basic' authorization is currently the most widely used there is a special method for that. Example:

    HTTPConnection con = new HTTPConnection(this);
    con.addBasicAuthorization("protected-space", "goofy", "woof");

You can also add authorization info using the AuthorizationInfo class directly; in this case you must also specify the host and port.

Note that it is not possible to pick up authorization info from the browser (even though I would love to) because this would of course constitute a largish security problem (imagine an applet that gets all the username/passwords from the browser and sends them back to the server...). This means that the user of an applet might potentially have to enter information (s)he's already entered before.

Redirections

Redirections (status codes 301, 302, 303, 305) are handled automatically for the request methods GET and HEAD; other requests are not redirected as a redirection might change the conditions under which the request was made (this is mandated by the specs). An exception is the 303 response code - upon receipt of this a GET is issued at the new location, no matter what the original request method was. This is used primarily for scripts which are accessed via POST and want to redirect the client to a predetermined response. Note that many browsers erroneously show the behaviour reserved for 303 when confronted with a 302 response from a POST request, inspite of it being in direct violation of the specs.

If the request was redirected (it may even have been redirected multiple times) the final URL that delivered the response can be retrieved using the response's getEffectiveURL() method.

[HTTPClient]


Ronald Tschalär / 23 March 1997 / ronald@innovation.ch.