咸鱼

咸鱼是以盐腌渍后,晒干的鱼

0%

深入解析HTTP--POST请求

之前写的《深入解析HTTP–Chunk分块发送》 和 《深入解析HTTP–Multipart》 都是关于用POST请求上传文件,本文要讲的,是指POST请求传递字符数据。

我们用PostMan作为客户端,SpringBoot作为服务端,Wireshark抓包,分析一下每个请求的包结构,了解一下其中的区别。

一、最简单的传参

服务端代码:

1
2
3
4
5
@PostMapping("/post")
public ResponseEntity testpost(@RequestParam("name") String name){

return ResponseEntity.ok("ok:"+name);
}

postman上有两种方式可以完成这个请求:

  1. URL中带参数

    这样的请求就相当于GET请求了,从下面的请求抓包也可以看出,基本和GET请求一样,要注意的是参数如果有中文等则需要编码。
    ** 网络抓包 **
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    POST /post?name=kevin HTTP/1.1
    Host: 192.168.0.223:8080
    content-length: 0

    HTTP/1.1 200
    Content-Type: text/plain;charset=UTF-8
    Content-Length: 8
    Date: Sat, 20 Jul 2019 04:37:55 GMT

    ok:kevin
  2. Body中带参数(application/x-www-form-urlencoded)
    客户端要在Header加 Content-Type: application/x-www-form-urlencoded

    ** 网络抓包 **
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    POST /post HTTP/1.1
    Host: 192.168.0.223:8080
    Content-Type: application/x-www-form-urlencoded
    content-length: 9
    Connection: keep-alive

    name=evalHTTP/1.1 200
    Content-Type: text/plain;charset=UTF-8
    Content-Length: 7
    Date: Sat, 20 Jul 2019 04:39:53 GMT

    ok:eval

    注意:请求体的Body之后没有换行符(/r/n),所以抓包的响应体HTTP/1.1 200 没有换行

个人觉得,POST的数据就应该放在Body里面,如本例子,本例子Body体的参数带有中文也是没有问题的。

二、发送文本

服务端代码

1
2
3
4
5
@PostMapping("/post/txt")
public ResponseEntity testPostText(@RequestBody() String body){

return ResponseEntity.ok("body:"+body);
}

客户端发送文本要在Header加 Content-Type: text/plain

请求

响应

** 网络抓包 **

1
2
3
4
5
6
7
8
9
10
11
12
POST /post/txt HTTP/1.1
Host: 192.168.0.223:8080
Content-Type: text/plain
content-length: 6
Connection: keep-alive

......HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 11
Date: Sat, 20 Jul 2019 08:59:44 GMT

body:......

......是中文字符 “你好”

三、发送JSON

服务端代码

1
2
3
4
5
@PostMapping("/post/json")
public ResponseEntity testPostText(@RequestBody() Object object){

return ResponseEntity.ok(object);
}

客户端发送JSON要在Header加 Content-Type: application/json

请求

响应

** 网络抓包 **

1
2
3
4
5
6
7
8
9
10
11
12
POST /post/json HTTP/1.1
Content-Type: application/json
Host: 192.168.0.223:8080
content-length: 29
Connection: keep-alive

{"name": "json", "age":"222"}HTTP/1.1 200
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Sat, 20 Jul 2019 09:24:02 GMT

{"name":"json","age":"222"}