Serving HTTP Content


Socket client = serverSocket.accept(); BufferedReader in =    new BufferedReader(new InputStreamReader(                       client.getInputStream())); // before serving a response, typically you would // read the client input and process the request. PrintWriter out =    new PrintWriter(client.getOutputStream()); out.println("HTTP/1.1 200"); out.println("Content-Type: text/html"); String html = "<html><head><title>Test Response" +    "</title></head><body>Just a test</body></html>"; out.println("Content-length: " + html.length()); out.println(html); out.flush(); out.close();



In this phrase, we show an example of serving a very simple piece of HTML content via HTTP. We accept a connection with a client, create a BufferedReader to read the client's request, and create a PrintWriter, which we use to send HTML via HTTP back to the client. The data that we write to the PrintWriter is the minimum necessary to create a valid HTTP response message. Our response consists of three HTTP header fields and our HTML data. We start our response by specifying the HTTP version and a response code in this line:

out.println("HTTP/1.1 200");


We are returning HTTP version 1.1 and a response code of 200. The response code of 200 indicates a successful request. In the next line, we specify the content type we are returning as HTML. We could return content types other than HTML and still have a valid HTTP response message. For example, the following would specify that our response is plaintext instead of HTML:

out.println("Content-Type: text/plain");


The next thing we write is the Content-length header. This specifies the length of the actual content being returned and does not include the header fields. After that, we write the actual HTML message that we are returning. Finally, we flush and close the BufferedReader stream using the flush() and close() methods.

Note

Although this technique is useful for simple HTTP serving requirements, I would not recommend trying to write your own complete HTTP server from scratch in Java. An excellent HTTP server is available freely as open source that is part of the Apache Jakarta project. This is the Tomcat server. You can get more information about Tomcat and download it from http://jakarta.apache.org/tomcat/. Not only does Tomcat serve HTTP, but it also contains a servlet container to handle Java Servlets and JSPs.





JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net