HTTP サーバのGETの例
単純にHello Worldを表示する例。
起動し、http://localhost:8080/にアクセスすると表示される。
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 HelloWorldServer { public static void main(String[] args) throws IOException { int port = 8080; HttpServer server = HttpServer.create(new InetSocketAddress(port), 0); server.createContext("/", new HttpHandler() { @Override public void handle(HttpExchange arg0) throws IOException { String str = "Hello World"; arg0.sendResponseHeaders(200, str.length()); OutputStream body = arg0.getResponseBody(); body.write(str.getBytes()); } }); server.start(); System.out.println("hit any key"); System.in.read(); server.stop(0); } }