views:

107

answers:

6

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

+3  A: 

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.

James Anderson
I think jetty api depends on servlet.
irreputable
@Irreputable: No, Jetty is a highly modular web server, which has a servlet container as one of it's optional modules.
Software Monkey
"is ther an analog for server functionality" -- yes its the "servlet" API. The servlet container calls your class after it has parsed the headers, cookies etc.
James Anderson
Software Monkey: you can't use it without servlet api. as long as we are using the silly notions of java se/ee, jetty is not se.
irreputable
+3  A: 

Check out NanoHttpd

letronje
One caution: It's likely that NanoHTTPD does not have protection against tree-walking attacks - you should check this if it will be serving on a public address. By this I mean attacks where a request like `GET /../../blahblah http/1.1` is issued and the server walks above the website root and into system file land, serving files that can be used to compromise or remotely attack the system, like a password file.
Software Monkey
+3  A: 

Since Java 1.6, there's a builtin HTTP server somewhere hidden in the depths of the Java API. The com.sun.net.httpserver package summary outlines the involved classes and contains examples.

Here's a (basic) kickoff example based on the docs, you can just copy'n'paste'n'run it on Java 1.6

package com.example;

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

}

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

This is the response

BalusC
Absolutely a -1 vote - do not use non-public unpublished classes from Sun/Oracle.
Software Monkey
@Software Monkey - why not? It seems to satisfy asker's requirements.
emory
@Software: it's not. Even more, it's documented.
BalusC
A: 

it's possible, because there are so many http servers written in pure java.

question is, how come there is no well-known, simple http server in java. (jetty is not simple enough). that's a good question. I'm sure if you google "simple java http server" there's a ton of simple implementations. but there isn't a "famous" one. maybe java people mostly do web apps and they've already got a non-simple http server.

a simple yet powerful http server can be implemented under 1000 lines of java.

irreputable
This answer isn't helpful.
Michael Brewer-Davis
A: 

I can strongly recommend looking into Simple, especially if you don't need Servlet capabilities but simply access to the request/reponse objects. If you need REST you can put Jersey on top of it, if you need to output HTML or similar there's Freemarker. I really love what you can do with this combination, and there is relatively little API to learn.

Waldheinz
A: 

You may also have a look at some NIO application framework such as:

  1. Netty: http://jboss.org/netty
  2. Apache Mina: http://mina.apache.org/ or its subproject AsyncWeb: http://mina.apache.org/asyncweb/
ThiamTeck