Created
August 6, 2013 09:18
-
-
Save oldratlee/6163025 to your computer and use it in GitHub Desktop.
A simple demo of com.sun.net.httpserver.HttpServer.
JavaDoc: http://docs.oracle.com/javase/7/docs/jre/api/net/httpserver/spec/com/sun/net/httpserver/HttpServer.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.sun.net.httpserver.HttpExchange; | |
import com.sun.net.httpserver.HttpHandler; | |
import com.sun.net.httpserver.HttpServer; | |
import java.io.IOException; | |
import java.io.OutputStream; | |
import java.net.InetSocketAddress; | |
import java.util.concurrent.Executors; | |
public class HttpServerTest { | |
public static void main(String[] args) throws Exception { | |
HttpServer httpServer = HttpServer.create(new InetSocketAddress(8888), 0); | |
httpServer.setExecutor(Executors.newCachedThreadPool()); | |
httpServer.createContext("/home", new HttpHandler() { | |
@Override | |
public void handle(HttpExchange httpExchange) throws IOException { | |
final byte[] out = "Hello, world!".getBytes("UTF-8"); | |
httpExchange.sendResponseHeaders(200, out.length); | |
OutputStream os = httpExchange.getResponseBody(); | |
os.write(out); | |
os.close(); | |
} | |
}); | |
httpServer.createContext("/apps", new HttpHandler() { | |
@Override | |
public void handle(HttpExchange httpExchange) throws IOException { | |
final byte[] out = "Apps Page!".getBytes("UTF-8"); | |
httpExchange.sendResponseHeaders(200, out.length); | |
OutputStream os = httpExchange.getResponseBody(); | |
os.write(out); | |
os.close(); | |
} | |
}); | |
httpServer.createContext("/apps/foo", new HttpHandler() { | |
@Override | |
public void handle(HttpExchange httpExchange) throws IOException { | |
final byte[] out = "Foo Page!".getBytes("UTF-8"); | |
httpExchange.sendResponseHeaders(200, out.length); | |
OutputStream os = httpExchange.getResponseBody(); | |
os.write(out); | |
os.close(); | |
} | |
}); | |
httpServer.start(); | |
System.out.println("HttpServer Test Start!"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I am implementing an HTTP server based on this. will be public in a few days. just in case someone reaches here: https://github.com/ssi-anik/remote-peripheral-control-server