美文网首页
Java Socket解析HTTP请求

Java Socket解析HTTP请求

作者: 史啸天 | 来源:发表于2021-06-18 20:18 被阅读0次

概述

Java解析HTTP请求,话不多说上代码:

/**
 * @author sxt
 * @date 2021-06-18
 * @describe 自己解析请求
 */
public class SocketTest {

    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("localhost", 10050);
        // 创建请求流
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8);
        // 写入地址等信息
        outputStreamWriter.write("GET /api/cmscore/template/config/info?configId=5 HTTP/1.1\r\n");
        outputStreamWriter.write("Host:localhost\r\n");
        outputStreamWriter.write("Cookie:user_id=10001; timestamp=1623933567011; token=eyJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJVU0VSX0NFTlRFUiIsInN1YiI6IntcImlkXCI6MTAwMDEsXCJuYW1lXCI6XCLns7vnu5_nrqHnkIblkZhcIixcImVtYWlsXCI6XCJhZG1pbkBsaWx5ZW5nbGlzaC5jb21cIixcInBob25lXCI6XCIxNjgqKioqMDAwMFwiLFwic3RhdHVzXCI6MSxcInR5cGVcIjoyLFwibG9naW5EYXRlXCI6XCIyMDIxLTA2LTEzIDEwOjI5OjU2XCIsXCJleHBpcmVEYXRlXCI6XCIyMDIxLTA3LTEzIDEwOjI5OjU2XCIsXCJkdXJhdGlvblwiOjI1OTIwMDB9IiwiYXVkIjoiTElMWV9kZXYiLCJpYXQiOjE2MjM1NTEzOTYsImV4cCI6MTYyNjE0MzM5Nn0.nAEp47o61CDoY0yzB1wYuHImZtNKFwGqTUF-QGKxXpVPYV_bsKvJ1LHzA3LFjROrLoMXhttQX8UD1nyaazDPoA; source=employeecom.lily.usercenter.UserCenterApp");
        outputStreamWriter.write("\r\n");
        outputStreamWriter.write("\r\n");
        outputStreamWriter.flush();
        socket.shutdownOutput();
        // 获取输入流
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
        String line = null;
        // 循环响应结果
        while((line = bufferedReader.readLine()) != null){
            System.out.println(line);
        }
        // 关闭流
        outputStreamWriter.close();
        bufferedReader.close();
        socket.close();
    }
}

总结

其实http协议,就是特定格式的网络数据包,我们只需要根据不同的场景拼接出特定的格式,就可以完成一次http请求。
不过现在已经有很多框架,底层实现了对http请求的解析和封装,我们无需再关注,但是在不依赖框架的情况下,还是需要知道其中原理。

相关文章

网友评论

      本文标题:Java Socket解析HTTP请求

      本文链接:https://www.haomeiwen.com/subject/zxslyltx.html