MENU

Java HttpServer 简单使用注释

November 20, 2020 • Read: 65 • 默认分类

SimpleHTTPServer:

package programming3.topic7.example2;

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;

public class SimpleHTTPServer {
    public static void main(String[] args) throws IOException {
        //创建http服务器,绑定本地80端口    0:int backlog 能同时接 受0个请求?
        HttpServer server = HttpServer.create(new InetSocketAddress(80), 0);
        //指定url和相应的处理Handler,创建上下文监听,拦截包含/... 的请求
        /**
         * 创建监听的上下文, 请求 URI 根路径的匹配, 根据不同的 URI 根路径选择不同的 HttpHandler 处理请求,
         * 路径必须以 "/" 开头。路径 "/" 表示匹配所有的请求 URI(没有其他更具体的匹配路径除外)。
         * HttpContext createContext​(String path)
         * HttpContext createContext​(String path, HttpHandler handler)
         */
        server.createContext("/", new SimpleHTTPHandler("Default handler"));
        server.createContext("/context1", new SimpleHTTPHandler("Context 1"));
        server.createContext("/context1/sub", new SimpleHTTPHandler("Sub context 1"));
        
        
        server.createContext("/context2", new HttpHandler() {
            @Override
            public void handle(HttpExchange exchange) throws IOException {
                System.out.println("Context 2");
                System.out.println();
                String response = "Context 2";
                exchange.sendResponseHeaders(200, response.getBytes("UTF-8").length);
                OutputStream output = exchange.getResponseBody();
                output.write(response.getBytes("UTF-8"));
                output.close();
            }
        });
        
        server.start();
    }
}

SimpleHTTPHandler:

package programming3.topic7.example2;

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

import java.io.*;

public class SimpleHTTPHandler implements HttpHandler {
    private final String response;

    public SimpleHTTPHandler(String response) {
        this.response = response;
    }

    /*
        URI getRequestURI​()--- 获取请求的 URI, 请求链接除去协议和域名端口后的部分, 如: http://www.abc.com/aa/bb, URI 为 /aa/bb
        InetSocketAddress getRemoteAddress​()--- 获取请求客户端的 IP 地址
        Headers getRequestMethod()--- 获取请求的方法, "GET", "POST" 等
        
        Headers getRequestHeaders​()--- 获取所有的请求头
        InputStream getRequestBody​()---以输入流的方式获取请求内容,返回一个可以读取请求内容的流

        Headers getResponseHeaders​()--- 获取响应头的 Map, 要添加头, 获取到 headers 后调用 add(key, value) 方法添加
        OutputStream getResponseBody​()--- 获取响应内容的输出流, 响应内容写到该流 响应主体被写入的流 
    */
    @Override
    public void handle(HttpExchange exchange) throws IOException {
        System.out.println("Requested URI: " + exchange.getRequestURI());         //控制台输出请求的 URI
        System.out.println("Client: " + exchange.getRemoteAddress());        //控制台输出请求客户端的 IP 地址
        System.out.println("Request method: " + exchange.getRequestMethod());        //控制台输出方法
        System.out.println("Request headers: " + exchange.getRequestHeaders().entrySet());        //控制台输出请求头
        
        //字符输入流中读取 获取请求内容 并缓冲字符
        BufferedReader reader = new BufferedReader(new InputStreamReader(exchange.getRequestBody()));
        //输出请求内容
        System.out.println("Request body: ");
        for (String line = reader.readLine(); line != null; line = reader.readLine()) {
            System.out.println(line);
        }
        
        System.out.println("Sending response: " + response);
        
        exchange.sendResponseHeaders(200, response.getBytes("UTF-8").length);
        //字符输出流中写入响应内容
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(exchange.getResponseBody()));
        writer.write(response);
        writer.flush();
        writer.close();
        System.out.println();
    }
}

SimpleClient:

package programming3.topic7.example2;

import java.io.*;

import static programming3.topic7.example1.SimpleHTTPClient.*;

public class SimpleClient {
    public static void main(String[] args) throws IOException {
        printPage("http://localhost");
        System.out.println();
        sendData("http://localhost/context1", "Hello World!");
        System.out.println();
        sendData("http://localhost/context1/sub", "Hello World!");
        System.out.println();
        sendData("http://localhost/context2", "Hello World!");
        System.out.println();
        sendData("http://localhost/context2/sub", "Hello World!");
        System.out.println();
        sendData("http://localhost/context3", "Hello World!");
        System.out.println();
        sendData("http://localhost", "Hello World!");
        System.out.println();
        httpRequest("http://localhost", "GET", null);
        System.out.println();
        httpRequest("http://localhost", "POST", "Hello World!");
        System.out.println();
        httpRequest("http://localhost", "DELETE", null);
    }


    public static void printPage(String address) throws MalformedURLException {
        URL url = new URL(address);
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(url.openStream()));
            for (String line = reader.readLine(); line != null; line = reader.readLine()) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void sendData(String address, String query) throws IOException {
        URL url = new URL(address);
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
        writer.write(query);
        writer.flush();
        writer.close();
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        for (String line = reader.readLine(); line != null; line = reader.readLine()) {
            System.out.println(line);
        }
    }

    public static void httpRequest(String address, String method, String query) throws IOException {
        URL url = new URL(address);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod(method);
        if (query != null) {
            connection.setDoOutput(true);
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
            writer.write(query);
            writer.flush();
            writer.close();
        }
//        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
//        for (String line = reader.readLine(); line != null; line = reader.readLine()) {
//            System.out.println(line);
//        }
        try {
            System.out.println("Response: " + connection.getResponseCode() + " " + connection.getResponseMessage());
        } catch (IOException e) {
            System.out.println("You have read all the message! Localhost did not send any data. There isn't a status line. ERR_EMPTY_RESPONSE ");
        }

    }
}
Last Modified: November 28, 2020
Archives QR Code Tip
QR Code for this page
Tipping QR Code