simple HTTP server in Java using only Java SE API

java http server example post
java 11 http server
java http server source code
java http server github
java http server socket
java async http server
java server
create web server using java

Is there a way to create a very basic HTTP server (supporting only GET/POST) in Java using just the Java SE API, without writing code to manually parse HTTP requests and manually format HTTP responses? The Java SE API nicely encapsulates the HTTP client functionality in HttpURLConnection, but is there an analog for HTTP server functionality?

Just to be clear, the problem I have with a lot of ServerSocket examples I've seen online is that they do their own request parsing/response formatting and error handling, which is tedious, error-prone, and not likely to be comprehensive, and I'm trying to avoid it for those reasons.

As an example of the manual HTTP manipulation that I'm trying to avoid:

http://java.sun.com/developer/technicalArticles/Networking/Webserver/WebServercode.html


Since Java SE 6, there's a builtin HTTP server in Sun Oracle JRE. The com.sun.net.httpserver package summary outlines the involved classes and contains examples.

Here's a kickoff example copypasted from their docs (to all people trying to edit it nonetheless, because it's an ugly piece of code, please don't, this is a copy paste, not mine, moreover you should never edit quotations unless they have changed in the original source). You can just copy'n'paste'n'run it on Java 6+.

package com.stackoverflow.q3732109;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

public class Test {

    public static void main(String[] args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
        server.createContext("/test", new MyHandler());
        server.setExecutor(null); // creates a default executor
        server.start();
    }

    static class MyHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange t) throws IOException {
            String response = "This is the response";
            t.sendResponseHeaders(200, response.length());
            OutputStream os = t.getResponseBody();
            os.write(response.getBytes());
            os.close();
        }
    }

}

Noted should be that the response.length() part in their example is bad, it should have been response.getBytes().length. Even then, the getBytes() method must explicitly specify the charset which you then specify in the response header. Alas, albeit misguiding to starters, it's after all just a basic kickoff example.

Execute it and go to http://localhost:8000/test and you'll see the following response:

This is the response


As to using com.sun.* classes, do note that this is, in contrary to what some developers think, absolutely not forbidden by the well known FAQ Why Developers Should Not Write Programs That Call 'sun' Packages. That FAQ concerns the sun.* package (such as sun.misc.BASE64Encoder) for internal usage by the Oracle JRE (which would thus kill your application when you run it on a different JRE), not the com.sun.* package. Sun/Oracle also just develop software on top of the Java SE API themselves like as every other company such as Apache and so on. Using com.sun.* classes is only discouraged (but not forbidden) when it concerns an implementation of a certain Java API, such as GlassFish (Java EE impl), Mojarra (JSF impl), Jersey (JAX-RS impl), etc.

A Simple HTTP Server in Java, In this article, we discuss how to create a simple HTTP server in Java that can With just three to four lines of code, we created an HTTP server with a context root that Create and Publish Your Rest API Using Spring Boot and Heroku. SKP's Java/Java EE Gotchas: Revisiting Java SE 9 Features, Part 2. How can we create HTTP server (supporting only GET/POST) in Java using just the Java SE API, without writing code to manually parse HTTP requests and manually format HTTP responses? The Java SE API nicely encapsulates the HTTP client functionality in HttpURLConnection, but is there an analog for HTTP server functionality?


Check out NanoHttpd

"NanoHTTPD is a light-weight HTTP server designed for embedding in other applications, released under a Modified BSD licence.

It is being developed at Github and uses Apache Maven for builds & unit testing"

Recent in Java, How can we create HTTP server (supporting only GET/POST) in Java using just the Java SE API but is there an analog for HTTP server  Simple HTTP server in Java using only Java SE API 0 votes Is there a way to create a very basic HTTP server (supporting only GET/POST) in Java using just the Java SE API, without writing code to manually parse HTTP requests and manually format HTTP responses?


The com.sun.net.httpserver solution is not portable across JREs. Its better to use the official webservices API in javax.xml.ws to bootstrap a minimal HTTP server...

import java.io._
import javax.xml.ws._
import javax.xml.ws.http._
import javax.xml.transform._
import javax.xml.transform.stream._

@WebServiceProvider
@ServiceMode(value=Service.Mode.PAYLOAD) 
class P extends Provider[Source] {
  def invoke(source: Source) = new StreamSource( new StringReader("<p>Hello There!</p>"));
}

val address = "http://127.0.0.1:8080/"
Endpoint.create(HTTPBinding.HTTP_BINDING, new P()).publish(address)

println("Service running at "+address)
println("Type [CTRL]+[C] to quit!")

Thread.sleep(Long.MaxValue)

EDIT: this actually works! The above code looks like Groovy or something. Here is a translation to Java which I tested:

import java.io.*;
import javax.xml.ws.*;
import javax.xml.ws.http.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;

@WebServiceProvider
@ServiceMode(value = Service.Mode.PAYLOAD)
public class Server implements Provider<Source> {

    public Source invoke(Source request) {
        return  new StreamSource(new StringReader("<p>Hello There!</p>"));
    }

    public static void main(String[] args) throws InterruptedException {

        String address = "http://127.0.0.1:8080/";
        Endpoint.create(HTTPBinding.HTTP_BINDING, new Server()).publish(address);

        System.out.println("Service running at " + address);
        System.out.println("Type [CTRL]+[C] to quit!");

        Thread.sleep(Long.MAX_VALUE);
    }
}

Java - HttpServer Example, Is there a way to create a very basic HTTP server (supporting only GET/POST) in Java using just the Java SE API, without writing code to  Sun/Oracle also just develop software on top of the Java SE API themselves like as every other company such as Apache and so on. Using com.sun.* classes is only discouraged (but not forbidden) when it concerns an implementation of a certain Java API, such as GlassFish (Java EE impl), Mojarra (JSF impl), Jersey (JAX-RS impl), etc.


HttpServer (Java HTTP Server ), The package com.sun.net.httpserver provides Http server API, which can be used to build To get started with this API, we need to get familiar with the following classes: It has only one method: JDK 10; Maven 3.3.9  source - simple HTTP server in Java using only Java SE API java lightweight http server (12) Is there a way to create a very basic HTTP server (supporting only GET/POST) in Java using just the Java SE API, without writing code to manually parse HTTP requests and manually format HTTP responses?


Have a look at the "Jetty" web server Jetty. Superb piece of Open Source software that would seem to meet all your requirments.

If you insist on rolling your own then have a look at the "httpMessage" class.

Create a simple HTTP Web Server in Java - Sylvain Saurel, For example. Given a HttpServer with the following HttpContexts configured. Context, Context path. ctx1, "/". ctx2, "  Since Java SE 6, there's a builtin HTTP server in Oracle JRE. The com.sun.net.httpserver package summary outlines the involved classes and contains examples. ref: stackoverflow


Have a simple HTTP server, Java is one of the most used programming language in the World. The JDK comes with a lot of exciting features. In that and the Socket classes to create a simple HTTP Web Server in Java. We support only GET and HEAD HTTP methods. Building a Spring Boot REST API — Part 3: Integrating MySQL  Simple HTTP server in java. Running the Server. java -jar http-server.jar -p 5000 -d public -p: is the port the server will run on. -d: is the relative directory to the http-server.jar file that the server will look for its content files from. Passing in invalid parameters will default the server to port 5000 with a directory of "public".


Create a Simple Web Server in Java (1) - HTTP Server, Since Java 1.6, there's a built-in HTTP server included with the JDK. The HttpServer provides a simple high-level Http server API, which can be used to build  This time its about HTTP server implementation using Java. Most of Java programmers have implemented TCP socket servers when stepping in to Java world. Thereafter developers compare Java with other languages, and think that implementing a server with Java is pretty hard.


How to create HTTP Server in Java - ServerSocket , Create a simple Http Server using Java SDK and process GET/POST The HttpServer class provides a simple high-level Http server API,  depuis Java SE 6, Il y a un serveur HTTP intégré dans Sun Oracle JRE. Le com.sun.net.httpserver sommaire du paquet décrit les classes concernées et contient des exemples.