[java] Create a simple HTTP server with Java?

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?

This question is related to java http post get

The answer is


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


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();
}

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


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/


I have implemented one link

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


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


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


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.


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


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.


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.


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.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to http

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Axios Delete request with body and headers? Read response headers from API response - Angular 5 + TypeScript Android 8: Cleartext HTTP traffic not permitted Angular 4 HttpClient Query Parameters Load json from local file with http.get() in angular 2 Angular 2: How to access an HTTP response body? What is HTTP "Host" header? Golang read request body Angular 2 - Checking for server errors from subscribe

Examples related to post

How to post query parameters with Axios? How can I add raw data body to an axios request? HTTP POST with Json on Body - Flutter/Dart How do I POST XML data to a webservice with Postman? How to set header and options in axios? Redirecting to a page after submitting form in HTML How to post raw body data with curl? How do I make a https post in Node Js without any third party module? How to convert an object to JSON correctly in Angular 2 with TypeScript Postman: How to make multiple requests at the same time

Examples related to get

Getting "TypeError: failed to fetch" when the request hasn't actually failed java, get set methods For Restful API, can GET method use json data? Swift GET request with parameters Sending a JSON to server and retrieving a JSON in return, without JQuery Retrofit and GET using parameters Correct way to pass multiple values for same parameter name in GET request How to download HTTP directory with all files and sub-directories as they appear on the online files/folders list? Curl and PHP - how can I pass a json through curl by PUT,POST,GET Making href (anchor tag) request POST instead of GET?