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

我最開始學習 Java web 編程是要去寫一個 servlet, 重寫裏面的 service 方法,而後去配置 web.xml 文件,最後就是部署到 tomcat 或者 jetty 容器中並啓動。後來就是使用一些框架,struts2 SpringMvc。今天我瞎翻 JDK 的源代碼,發現能夠用 com.sun.net.httpserver 包下提供的 API 很快速的建立 web 服務,它的建立方式和 golang 極其的相似。javascript

HttpHandler

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

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

建立 web 服務

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

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, 下面是我寫了兩個完整的例子。web

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"}
複製代碼
相關文章
相關標籤/搜索