Menu

java simple httpserver

Today when i need a customer httpserver,I find sun's httpserver.

It's very easy to do some test.

Below are the simple code.

package com.chenze.android.httpserver;

import java.io.IOException;
import java.io.InputStream;
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 MyHttpServer {

    public MyHttpServer(){

    }

    public void init() throws IOException{
        HttpServer httpServer = HttpServer.create(new InetSocketAddress(8888),0);
        httpServer.createContext("/",new MyHttpHandler());
        httpServer.setExecutor(null);
        httpServer.start();
    }

    public static void main(String[]args) throws IOException{
        MyHttpServer server = new MyHttpServer();
        server.init();
    }

}

class MyHttpHandler implements HttpHandler{
    public void handle(HttpExchange t) throws IOException {
        InputStream is = t.getRequestBody();
        String response = "<h3>Zilla's HttpServer Start!</h3>";
        t.sendResponseHeaders(200, response.length());
        OutputStream os = t.getResponseBody();
        os.write(response.getBytes());
        os.close();
    }
}
Posted by chanser 2012-06-15

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.