com.sun.net.httpserver.HttpServer を使ってみた

なんとなく眠れなかったので、サンプルつくってみたよ。

概要

  • メイン文の中で、HTTPサーバを立ち上げてます。
  • HttpHandler というインタフェースは handle というメソッドだけ持っていて、HTTPリクエストを受け取ってから返すまでの処理を記述します。引数は HttpExchange っていう HttpServletRequest と HttpServletResponse を併せ持ったようなやつです。ここでは、応答コード200 で "This is only a test." という文字列を返しています。
  • HttpServer は、ポート8080で初期化しています。
  • server#createContext() にて、"/kumakuma/" というパスでコンテキストを生成し、上記の HttpHandler を関連付けています。
  • server.start() にて、HttpServer を開始しています。
  • ブラウザから http://127.0.0.1:8080/kumakuma/ にアクセスすると、"This is only a test." という結果が返ります。

ソース

ソース

package jp.objectfanatics.ofcache.misc.httpserversample;

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;

/**
 * Sample program for HttpServer.
 *
 * @author beyondseeker
 *
 * $Id: HttpServerSample.java 46 2008-05-13 15:48:03Z beyondseeker $
 *
 */
public class HttpServerSample {
    
    public static void main(String[] args) throws Exception {
        
        // handler
        HttpHandler handler = new HttpHandler() {
            public void handle(HttpExchange he) throws IOException {
                System.out.print("start handle ... ");
                
                OutputStream os = he.getResponseBody();
                
                // response 200, chunk encoding.
                he.sendResponseHeaders(200, 0);
                
                // write text.
                os.write("This is only a test.".getBytes());
                
                // close
                os.close();
                
                System.out.println("done!");
            }
        };
        
        // port 8080
        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
        
        // set handler to context "/kumakuma/"
        server.createContext("/kumakuma/", handler);
        
        // start server
        server.start();
    }
    
}

軽くていい感じです。