java Socket实现HTTP服务器(一)简单例子

oyhk 学习笔记


这篇文章基于java Socket实现HTTP服务器,目前只是一个最为简单的例子。
我们看最简单的HTTPServer代码

HttpServer.java

package com.mkfree.sample.httpserver1;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;


public class HttpServer {

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8080, 1, InetAddress.getByName("127.0.0.1"));

        while (true) {
            Socket socket = serverSocket.accept();

            InputStream inputStream = socket.getInputStream();
            int input;
            StringBuilder requestMsg = new StringBuilder();
            while ((input = inputStream.read()) != -1) {
                requestMsg.append((char) input);
                // 暂时这样模拟http get 结束
                if (requestMsg.lastIndexOf("\r\n\r\n") != -1) {
                    break;
                }
            }
            System.out.println(requestMsg);


            // 返回数据
            String body = "{\"id\":1,\"name\":\"oyhk\"}";
            OutputStream outputStream = socket.getOutputStream();
            String response = "HTTP/1.1 200 OK\r\n" +
                    "Content-Type:application/json\r\n" +
                    "Content-Length:" + body.length() + "\r\n" +
                    "\r\n" + body;

            System.out.println(response);
            outputStream.write(response.getBytes());

            inputStream.close();
            outputStream.flush();
            outputStream.close();
            socket.close();
        }
    }
}

postman 请求:http://127.0.0.1:8080

HttpServer 打印结果:

GET / HTTP/1.1
Host: 127.0.0.1:8080
Connection: keep-alive
Cache-Control: no-cache
Content-Type: application/json
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36
Postman-Token: 11a34e79-c2b1-459f-13f5-d709bb13ac14
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8


HTTP/1.1 200 OK
Content-Type:application/json
Content-Length:22

{"id":1,"name":"oyhk"}

以上就是最简单的Socket模拟HttpServer

发表评论