com.sun.net.httpserver 建立 web 服務

Simeone_xu發表於2019-01-19

我最開始學習 Java web 程式設計是要去寫一個 servlet, 重寫裡面的 service 方法,然後去配置 web.xml 檔案,最後就是部署到 tomcat 或者 jetty 容器中並啟動。後來就是使用一些框架,struts2 SpringMvc。今天我瞎翻 JDK 的原始碼,發現可以用 com.sun.net.httpserver 包下提供的 API 很快速的建立 web 服務,它的建立方式和 golang 極其的類似。

HttpHandler

首先要實現 HttpHandler, 重寫 handle 方法。

public class MyHandler implements HttpHandler {
    @Override
    public void handle(HttpExchange httpExchange) throws IOException {
    
    }
}

建立 web 服務

建立 web 服務並註冊前面建立的 handler,使用 handler 來處理請求。

public class Main {

    public static void main(String[] args) {
        try {
            HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
            server.createContext("/web", new MyHandler());
            // 使用預設的 excutor
            server.setExecutor(null);
            server.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

只要執行這個 main 方法,一個 web 服務就啟動了,監聽埠是 8000, 下面是我寫了兩個完整的例子。

GetHandler

package me.deweixu.handler;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import netscape.javascript.JSObject;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

/**
 * Created by simeone
 *
 * @author: simeone
 * @Date: 2018/5/19
 */
public class GetHandler implements HttpHandler {
    @Override
    public void handle(HttpExchange httpExchange) throws IOException {
        System.out.println("Method: " + httpExchange.getRequestMethod());
        String param = httpExchange.getRequestURI().getQuery();
        System.out.println("Param:" + param);
        httpExchange.sendResponseHeaders(200, 0);

        OutputStream os = httpExchange.getResponseBody();
        os.write(param.getBytes());
        os.close();
    }

}

PostHandler

package me.deweixu.handler;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;

/**
 * Created by simeone
 *
 * @author: simeone
 * @Date: 2018/5/19
 */
public class PostHandler implements HttpHandler {
    @Override
    public void handle(HttpExchange httpExchange) throws IOException {
        System.out.println("Method: " + httpExchange.getRequestMethod());

        InputStream is = httpExchange.getRequestBody();
        String response = is2string(is);
        System.out.println("response: " + response);
        is.close();
        httpExchange.sendResponseHeaders(200, response.length());

        Headers headers = httpExchange.getResponseHeaders();
        headers.set("Content-Type", "application/json; charset=utf8");

        OutputStream os = httpExchange.getResponseBody();
        os.write(response.getBytes());
        os.close();
    }

    private String is2string(InputStream is) throws IOException {
        final int bufferSize = 1024;
        final char[] buffer = new char[bufferSize];
        final StringBuilder out = new StringBuilder();
        Reader in = new InputStreamReader(is, "UTF-8");
        for (; ; ) {
            int rsz = in.read(buffer, 0, buffer.length);
            if (rsz < 0)
                break;
            out.append(buffer, 0, rsz);
        }
        return out.toString();
    }
}

Main

package me.deweixu;

import com.sun.net.httpserver.HttpServer;
import me.deweixu.handler.GetHandler;
import me.deweixu.handler.PostHandler;

import java.io.IOException;
import java.net.InetSocketAddress;

public class Main {

    public static void main(String[] args) {
        try {
            HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
            server.createContext("/post", new PostHandler());
            server.createContext("/get", new GetHandler());
            server.setExecutor(null);
            server.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

測試

# get
$ curl http://127.0.0.1:8000/get?name=simeone&address=beijing
name=simeone&address=beijing

# post
$ curl -H "Content-Type: application/json" -d `{"username":"simeone", "address":"beijing"}` http://127.0.0.1:8000/post
{"username":"simeone", "address":"beijing"}

相關文章