views:

277

answers:

8

What's the easiest way to create a simple HTTP server with Java? Are there any libraries in commons to facilitate this? I only need to respond to GET/POST, and I can't use an application server.

What's the easiest way to accomplish this?

+3  A: 

If you are using the Sun JDK you can use this built in library
Look at this site on how to use.

If n ot there are several Open Source HTTP Servers here which you can embed into your software.

Romain Hippeau
+3  A: 

Use Jetty.

Tutorial

Jetty is pretty lightweight but it does provide a servlet container which may contradict your requirement against using an "application server".

Kris
Yup, more specifically [this link](http://wiki.eclipse.org/Jetty/Tutorial/Embedding_Jetty) is useful.
BalusC
Not using an "application server" was simply the requirement that I not run UNDER it. This quote sums it up quite nicely:"Don't deploy your application in Jetty, deploy Jetty in your application".
Stefan Kendall
A: 

Jetty is a great way to easily embed an HTTP server. It supports it's own simple way to attach handlers and is a full J2EE app server if you need more functionality.

maerics
A: 

Embedding Tomcat is relatively painless as such things go. Here's a good StackOverflow reference about it.

Dan
A: 

A servlet container is definitely the way to go. If Tomcat or Jetty are too heavyweight for you, consider Winstone or TTiny.

Michael Borgwardt
Do you have experience with TTiny?
Thorbjørn Ravn Andersen
A: 

The easiest is Simple there is a tutorial, no WEB-INF not Servlet API no dependencies. Just a simple lightweight HTTP server in a single JAR.

ng
A: 

This is how I would go about this:

  1. Start a ServerSocket listening (probably on port 80).
  2. Once you get a connection request, accept and pass to another thread/process (this leaves your ServerSocket available to keep listening and accept other connections).
  3. Parse the request text (specifically, the headers where you will see if it is a GET or POST, and the parameters passed.
  4. Answer with your own headers (Content-Type, etc.) and the HTML.

I find it useful to use Firebug (in Firefox) to see examples of headers. This is what you want to emulate.

Try this link: - Multi-threaded HTTP Server Example (Java)

Philippe Signoret