Http coding and testing

A few days ago I blogged about writing a dummy server to use for testing. However, rather than just writing on a socket, the code I’m writing uses http and as it happens, there are some useful libraries you can use to write and test http code.

To write a client, you might like to look at the Apache Commons HttpComponents:

http://hc.apache.org/httpcomponents-client-ga/

For writing a server, there is actually some code bundled with the Sun Java distribution. It is in the com.sun package, so is not officially part of Java, but it is included in rt.jar.

http://download.oracle.com/javase/6/docs/jre/api/net/httpserver/spec/index.html

To write a server, you need to:

  1. Create your server.
  2. Create at least one HttpHandler.
  3. Map the HttpHandler to a context path.
  4. Bind the server to an IP address and port.
  5. Start the server.

My trial code was:

// create a dummy server
HttpServer server = HttpServer.create();
// define an anonymous class to act as an httphandler
HttpHandler myHandler = new HttpHandler() {
BufferedReader reader;
PrintWriter out;

public void handle(HttpExchange exchange) {
  System.out.println(exchange.getRequestMethod());
  try {
    // http response code 200 is success
    exchange.sendResponseHeaders(200, 0);
  }
  catch (IOException e1) {
    log.error(e1);
  }

  System.out.println(exchange.getRequestURI().toString());

  reader = new BufferedReader(new InputStreamReader(exchange.getRequestBody()));
  try {
    System.out.println("Input: " + reader.readLine());
  }
  catch (IOException e) {
  log.error(e);
  }

  out = new PrintWriter(exchange.getResponseBody());
  out.println("Hello from server");
  out.flush();
  exchange.close();
  }
};

server.createContext("/",myHandler);
InetSocketAddress address = new InetSocketAddress("localhost", 35297);
server.bind(address, 5);
server.start();

You can see that this handler just prints out the various parts of the http request.

For the client code, I used the old v3.1 Apache Commons httpclient:

HttpClient httpclient = new HttpClient();
HttpMethod postBasket = new PostMethod("http://localhost:35297?data=something");
int statusCode = httpclient.executeMethod(postBasket);

if (statusCode != HttpStatus.SC_OK) {
System.out.println("Method failed: " + postBasket.getStatusLine());
}

String response = postBasket.getResponseBodyAsString();
System.out.println("Response from server: " + response);

The output from running this code is:

POST
/?data=something
Input: null
Response from server: Hello from server

This is as expected – on this occasion the client has only issued a POST request, it hasn’t written anything into the body of the request, so the input stream opened on the body is null.

This entry was posted in Java and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

505,038 Spambots Blocked by Simple Comments

HTML tags are not allowed.