前言
简单介绍http协议解析的规则,以及使用原生java socket模拟发送http请求,解析http响应等。
http请求
- 请求行(GET /v1/users/1 HTTP/1.1)
请求头
Accept: text/html,application/xhtml+xml,application/xml;
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.8
Cache-Control: max-age=0
Connection: keep-alive
Host: 127.0.0.1
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)
Content-Length: 100
Content-Type: application/json请求体(body:可以是json字符串,普通文本,xml字符串,文件等)
请求报文结构:GET /v1/users/1 HTTP/1.1[CRLF] ——> 请求行[Request-Line]
Accept-Encoding: gzip, deflate, br[CRLF] ——> 请求头[Request-Header]
Content-Length: 67[CRLF] ——> 请求头[Request-Header]
Content-Type: application/json[CRLF] ——> 请求头[Request-Header]
Host: 127.0.0.1[CRLF] ——> 请求头[Request-Header]
Cache-Control: max-age=0[CRLF] ——> 请求头[Request-Header]
Connection: keep-alive[CRLF] ——> 请求头[Request-Header]
[CRLF] ——> 请求头与请求body分隔符回车换行符CRLF:/r/n
{"age":25,"id":1,"password":"123456","status":1,"username":"lipan"}
http响应
- 响应行(HTTP/1.1 200 OK)
响应头
Content-Length: 67
Content-Type: text/html;charset=UTF-8
Date: Sun, 13 Aug 2017 09:00:07 GMT
Server: Apache-Coyote/1.1响应体(body:可以是json字符串,普通文本,xml字符串,文件等)
响应报文结构:HTTP/1.1 200 OK[CRLF] ——> 响应行[Response-Line]
Content-Length: 67[CRLF] ——> 请求头[Response-Header]
Content-Type: text/html;charset=UTF-8[CRLF] ——> 请求头[Response-Header]
Server: Apache-Coyote/1.1[CRLF] ——> 请求头[Response-Header]
Date: Sun, 13 Aug 2017 09:00:07 GMT[CRLF] ——> 请求头[Response-Header]
[CRLF] ——> 响应头与响应body分隔符回车换行符CRLF:/r/n
{"age":25,"id":1,"password":"123456","status":1,"username":"lipan"}
http协议模拟
package com.example; |
响应结果如下:responseLine protocol: HTTP/1.1
responseLine code: 200
responseLine msg: OK
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=UTF-8
Content-Length: 67
Date: Sun, 13 Aug 2017 09:46:19 GMT
响应体Body: {"age":25,"id":1,"password":"123456","status":1,"username":"lipan"}
示例代码:Http.java