什么是HTTP?
HyperText Transfer Protocol
超文本传输协议, 和 HTML ( HyperText Markup Language ) 一起诞生。
URL
Uniform Resource Locator
统一资源定位符
协议类型://服务器地址[:端口]/路径?参数
复制代码
HTTP报文
-
请求报文
//请求行: 请求方法 路径 HTTP协议版本 GET /torvalds?tab=repositories HTTP/1.1 //Header(非必须) start User-Agent: PostmanRuntime/7.26.10 Accept: */* Host: github.com ... Accept-Encoding: gzip, deflate, br Connection: keep-alive //Header end //请求体(非必须) 复制代码
-
响应报文
//状态行 HTTP协议版本 状态码 状态信息 HTTP/1.1 200 OK Server: GitHub.com Content-Type: text/html; charset=utf-8 <html>......<html> 复制代码
请求方法
以下请求报文都是虚构。请勿当真!!!
-
GET
GET方法的body为空
GET /torvalds?tab=repositories HTTP/1.1 Host: github.com 复制代码
-
POST
POST /shoe HTTP/1.1 Host: taobao.com type=basketball&&gender=male 复制代码
-
PUT
与POST类似
PUT /shoe HTTP/1.1 Host: taobao.com type=basketball&&gender=male 复制代码
-
DELETE
用于删除,没有body
DELETE /shoe HTTP/1.1 Host: taobao.com 复制代码
-
HEAD
与GET方法使用一样,区别是响应报文没有body
响应状态码
详细的状态码可以参考MDN状态码
-
1XX 临时消息(100 Continue, 101 Switching Protocol)
-
2XX 成功消息(200 OK, 201 Created)
-
3XX 重定向(301 Moved Permanently,304 Not Modified, 307 Temporary Redirect)
-
4XX 客户端错误(400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 405 Method Not Allowed)
-
5XX 服务器错误(500 Internal Server Error)
Header
-
Host
目标主机
-
Content-Type
- text/html 一般用于响应报文指定body为网页类型
HTTP/1.1 200 OK Server: GitHub.com Content-Type: text/html; charset=utf-8 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> 复制代码
- application/x-www-form-urlencoded 一般用于表单形式使用POST方法提交数据
POST / HTTP/1.1 Host: hikobe8.com Content-Type: application/x-www-form-urlencoded Content-Length: 13 say=Hi&to=Mom 复制代码
- multipart/form-data 文件上传,使用POST方法
POST /test.html HTTP/1.1 Host: example.org Content-Type: multipart/form-data;boundary="boundary" --boundary Content-Disposition: form-data; name="field1" value1 --boundary Content-Disposition: form-data; name="field2"; filename="example.txt" value2 复制代码
4.text/plain(纯文本), application/json (body为json格式), application/zip (body为压缩文件), application/jpeg (body为jepg图片文件)
-
Location
指定的是需要将页面重新定向至的地址。一般在响应码为3xx的响应中才会有意义
HTTP/1.1 307 Internal Redirect Location: https://github.com/ Non-Authoritative-Reason: HSTS 复制代码
-
User-Agent
客户端请求代理,一般作为请求的标识表示是浏览器还是手机等。
GET / HTTP/1.1 User-Agent: PostmanRuntime/7.26.10 Accept: */* Host: stackoverflow.com 复制代码
-
Accept-Range/Range
Accept-Ranges: none 复制代码
表示服务器不支持任何范围请求单位
Accept-Ranges: bytes 复制代码
表示服务器支持范围请求,单位是 bytes (字节)。
-
Content-Range
Conetnt-Range: bytes 0-23000/41893 复制代码
当前body所占字节起始位置/整个文件大小字节数
实战
最后我们使用Postman这个工具来模拟上面所述的Range参数发送HTTP请求显示图片来更加形象直观的理解Accept-Range/Range Content-Range
- 首先找一张图片在Postma中直接请求
这次请求是一张完整的图片
- 查看这次请求的Response Header
可以看出
Content-Length: 16574
Accept-Ranges: bytes
复制代码
所以我们可以在请求Header中使用Range参数进行范围获取数据
- 添加Range参数,发送请求
添加了Range:bytes=0-8574
之后发现只能加载出帽子了。
- 查看添加Range参数的Response Header
Content-Range: bytes 0-8754/16574
复制代码
我们可以清楚的看到当前请求的起始字节数和资源总字节大小
实战总结:使用 Accept-Range/Range, Content-Range,可以实现多线程下载,断点续传等功能。
写在最后
学习HTTP推荐一本书
还有MDN
MDN