68

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?

Stefan Kendall
  • 66,414
  • 68
  • 253
  • 406
  • This thread provide example in which native Java libraries are used. [1]: http://stackoverflow.com/questions/3732109/simple-http-server-in-java-using-only-java-se-api – Masoud Valafar Jun 30 '14 at 20:56
  • Here had put Blog for how to use Jetty.https://wxg-blog.blogspot.com/2019/08/javahow-to-use-jetty-build-simple-http.html – Guokas Aug 20 '19 at 00:54

13 Answers13

47

Use Jetty. Here's the official example for embedding Jetty. (Here's an outdated tutorial.)

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

You can embed the Jetty server into your application. Jetty allows EITHER embedded OR servlet container options.

Here is one more quick get started tutorial along with the source code.

Pavan Kumar
  • 4,182
  • 1
  • 30
  • 45
Kris
  • 14,426
  • 7
  • 55
  • 65
  • 3
    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 Apr 26 '10 at 22:25
  • jetty makes it hard to upload files while in embedded mode since 2012 (thats 7 years btw). I haven't found a single working example of file uploads with embedded jetty. Unless you want to serve static files that you put with another tecnology. Also jetty has poor docs – Dr Deo Jul 25 '19 at 20:56
36

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: - Multithreaded Server in Java

Philippe Signoret
  • 13,299
  • 1
  • 40
  • 58
  • 1
    @relgukxilef Indeed. I updated to a different site with similar content. The original link [is still available on Wayback Machine](https://web.archive.org/web/20120213174924/http://java.sun.com/developer/technicalArticles/Networking/Webserver). – Philippe Signoret Apr 29 '16 at 22:15
  • This should be the accepted answer, as the answer about Jetty is in direct conflict with the stated requirement of no application server. ServerSocket is as simple as it gets. – Kallaste Jun 09 '18 at 01:12
  • And to use Session, we have to use Java EE servlets API ? – R Sun Oct 11 '19 at 22:09
22

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.
  • 7,099
  • 1
  • 38
  • 42
8

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.

Community
  • 1
  • 1
Romain Hippeau
  • 24,113
  • 5
  • 60
  • 79
  • It is the Java 6 runtime, earlier versions did not ship with it. – Thorbjørn Ravn Andersen May 28 '12 at 22:47
  • Since java 8 it is blocked by default, you can allow access to the library with the accepted response here http://stackoverflow.com/questions/13155734/eclipse-cant-recognize-com-sun-net-httpserver-httpserver-package – Sfp Mar 10 '17 at 16:41
4

Java 6 has a default embedded http server.

Check the thread here

By the way, if you plan to have a rest web service, here is a simple example using jersey.

Community
  • 1
  • 1
Titu
  • 176
  • 7
4

I'm suprised this example is'nt here:

http://hc.apache.org/httpcomponents-core-ga/httpcore/examples/org/apache/http/examples/ElementalHttpServer.java

EDIT >> The above link is not reachable. Here is an excerpt from the POST example followed by the link to the HTTP examples.

 if (!conn.isOpen()) {
        Socket socket = new Socket(host.getHostName(), host.getPort());
        conn.bind(socket);
    }
    BasicHttpEntityEnclosingRequest request = new
    BasicHttpEntityEnclosingRequest("POST",
    "/servlets‐examples/servlet/RequestInfoExample");
    request.setEntity(requestBodies[i]);
    System.out.println(">> Request URI: " + request.getRequestLine().getUri());
    httpexecutor.preProcess(request, httpproc, coreContext);
    HttpResponse response = httpexecutor.execute(request, conn, coreContext);
    httpexecutor.postProcess(response, httpproc, coreContext);
    System.out.println("<< Response: " + response.getStatusLine());
    System.out.println(EntityUtils.toString(response.getEntity()));
    System.out.println("==============");
    if (!connStrategy.keepAlive(response, coreContext)) {
    conn.close();
    } else {
    System.out.println("Connection kept alive...");
    }

http://hc.apache.org/httpcomponents-core-ga/httpcore/examples/org/apache/http/examples/

AndiGeeky
  • 11,266
  • 6
  • 50
  • 66
nikdeapen
  • 1,581
  • 3
  • 15
  • 27
3

I wrote a tutorial explaining how to write a simple HTTP server a while back in Java. Explains what the code is doing and why the server is written that way as the tutorial progresses. Might be useful http://kcd.sytes.net/articles/simple_web_server.php

1

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.

Pavan Kumar
  • 4,182
  • 1
  • 30
  • 45
maerics
  • 151,642
  • 46
  • 269
  • 291
1

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

Community
  • 1
  • 1
Dan
  • 10,990
  • 7
  • 51
  • 80
1

I have implemented one link

N.B. for processing json, i used jackson. You can remove that also, if you need

akash
  • 727
  • 5
  • 13
0

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

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
0

Undertow is a lightweight non-blocking embedded web server that you can get up and running very quickly.

public static void main(String[] args) {
Undertow.builder()
        .addHttpListener(8080, "localhost")
        .setHandler((exchange) -> exchange.getResponseSender().send("hello world"))
        .build().start();
}
Bill O'Neil
  • 556
  • 3
  • 13
-1

I just added a public repo with a ready to run out of the box server using Jetty and JDBC to get your project started.

Pull from github here: https://github.com/waf04/WAF-Simple-JAVA-HTTP-MYSQL-Server.git

William Falcon
  • 9,813
  • 14
  • 67
  • 110