Get和Post各种编码方式和获取参数的问题

2024-02-07 15:38

本文主要是介绍Get和Post各种编码方式和获取参数的问题,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Get和Post各种编码方式和获取参数的问题

  做后端开发,会跟各种请求打交道,Get或者Post甚至其他,而就Get和Post不同的编码方式和content-type提交也有许多的不同,在开发过程中,经常遇到参数接收不到的问题,无论是原生servlet还是springboot框架,都有到过这种问题。这篇文中就这些问题,通过分析,希望能让自己能更进一步的了解HTTP请求和参数接收相关的原理。

Get请求

  Get请求比较简单,请求的参数为[key=value],通过&连接起来,一般被称为查询字符串(Query String),例如:http://127.0.0.1/test?name=strive&age=23,参数为:name=strive&age=23.

GET /get?name=strive HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
Sec-Fetch-Site: same-origin
Referer: http://localhost:8080/getAndPostIndex
Accept-Encoding: gzip, deflate, br

  其实我们只需要看/get?name=strive即查询参数,GET请求参数是被存放在QueryString 中的,这种在我们后台是可以通过request.getParameter() 获取请求参数的。

POST请求

  下面我们来看POST请求,POST请求的方式比Get复杂,它参数的存放位置是和Content-Type 有关系的,具体有什么关系,继续往下看。

Content-Type为application/x-www-form-urlencoded
POST /postUrl HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 11
Cache-Control: max-age=0
Origin: http://localhost:8080
Upgrade-Insecure-Requests: 1
Content-Type: application/x-www-form-urlencoded
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
Sec-Fetch-Site: same-origin
Referer: http://localhost:8080/getAndPostIndex
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9,ko;q=0.8,en;q=0.7
Form Data
name=strive

  这种方式提交的参数放在了以[key=value]方式存在了请求体中,这种在我们后台是也是可以通过request.getParameter() 获取请求参数的。

Content-Type为multipart/form-data
POST /postFileUpload HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 3768
Cache-Control: max-age=0
Origin: http://localhost:8080
Upgrade-Insecure-Requests: 1
#Content-Type为multipart/form-data
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary6A2xLxBKaSvqBvDd
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
Sec-Fetch-Site: same-origin
Referer: http://localhost:8080/getAndPostIndex
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9,ko;q=0.8,en;q=0.7
#Request的请求体
Request Payload
------WebKitFormBoundary6A2xLxBKaSvqBvDd
Content-Disposition: form-data; name="file"; filename="Baidu.cer"
Content-Type: application/x-x509-ca-cert
#这里省略了文件的数据
------WebKitFormBoundary6A2xLxBKaSvqBvDd
Content-Disposition: form-data; name="name"
strive
------WebKitFormBoundary6A2xLxBKaSvqBvDd--

  在Content-Type: multipart/form-data 时,而且POST提交的参数存放在了Request Payload,这种请求参数没办法通过request.getParameter() 获取请求参数的。

Content-Type为application/json
POST /postJson HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 13
Accept: */*
Origin: http://localhost:8080
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36
Sec-Fetch-Mode: cors
Content-Type: application/json
Sec-Fetch-Site: same-origin
Referer: http://localhost:8080/getAndPostIndex
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9,ko;q=0.8,en;q=0.7
#Request的请求体
Request Payload
{name:strive}

  在Content-Type: application/json 时,而且POST提交的参数存放在了Request Payload,这种请求参数没办法通过request.getParameter() 获取请求参数的。

Content-Type为text/plain
POST /postPlain HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 13
Cache-Control: max-age=0
Origin: http://localhost:8080
Upgrade-Insecure-Requests: 1
Content-Type: text/plain
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
Sec-Fetch-Site: same-origin
Referer: http://localhost:8080/getAndPostIndex
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9,ko;q=0.8,en;q=0.7
#Request的请求体
Request Payload
name=strive

  在Content-Type: text/plain 时,而且POST提交的参数存放在了Request Payload,这种请求参数没办法通过request.getParameter() 获取请求参数的。

POST请求的问题

  从上面的几个请求的报文的例子中我们可以找到一些规律,以application/x-www-form-urlencoded作POST提交的数据,后台是可以通过request.getParameter() 获取请求参数的。而multipart/form-data,application/jsontext/plain作POST提交数据时,后台没法通过request.getParameter() 获取请求参数的。application/x-www-form-urlencoded的参数放在了名为Form Data的请求体中,而其他的则放在了名为Request Payload的请求体中。那是什么原因了?
  解析请求参数的实现源码org.apache.catalina.connector.Request#parseParameters如下:

 protected void parseParameters() {this.parametersParsed = true;Parameters parameters = this.coyoteRequest.getParameters();boolean success = false;try {parameters.setLimit(this.getConnector().getMaxParameterCount());Charset charset = this.getCharset();boolean useBodyEncodingForURI = this.connector.getUseBodyEncodingForURI();parameters.setCharset(charset);if (useBodyEncodingForURI) {parameters.setQueryStringCharset(charset);}parameters.handleQueryParameters();if (this.usingInputStream || this.usingReader) {success = true;return;}//获取请求的contentTypeString contentType = this.getContentType();if (contentType == null) {contentType = "";}int semicolon = contentType.indexOf(59);if (semicolon >= 0) {contentType = contentType.substring(0, semicolon).trim();} else {contentType = contentType.trim();}//处理文件上传if ("multipart/form-data".equals(contentType)) {this.parseParts(false);success = true;return;}if (!this.getConnector().isParseBodyMethod(this.getMethod())) {success = true;return;}if ("application/x-www-form-urlencoded".equals(contentType)) {//如果是这种contenttype则解析int len = this.getContentLength();if (len <= 0) {if ("chunked".equalsIgnoreCase(this.coyoteRequest.getHeader("transfer-encoding"))) {Object var21 = null;Context context;byte[] formData;try {formData = this.readChunkedPostBody();} catch (IllegalStateException var17) {parameters.setParseFailedReason(FailReason.POST_TOO_LARGE);context = this.getContext();if (context != null && context.getLogger().isDebugEnabled()) {context.getLogger().debug(sm.getString("coyoteRequest.parseParameters"), var17);}return;} catch (IOException var18) {parameters.setParseFailedReason(FailReason.CLIENT_DISCONNECT);context = this.getContext();if (context != null && context.getLogger().isDebugEnabled()) {context.getLogger().debug(sm.getString("coyoteRequest.parseParameters"), var18);}return;}if (formData != null) {parameters.processParameters(formData, 0, formData.length);}}} else {int maxPostSize = this.connector.getMaxPostSize();Context context;if (maxPostSize >= 0 && len > maxPostSize) {context = this.getContext();if (context != null && context.getLogger().isDebugEnabled()) {context.getLogger().debug(sm.getString("coyoteRequest.postTooLarge"));}this.checkSwallowInput();parameters.setParseFailedReason(FailReason.POST_TOO_LARGE);return;}context = null;byte[] formData;if (len < 8192) {if (this.postData == null) {this.postData = new byte[8192];}formData = this.postData;} else {formData = new byte[len];}try {if (this.readPostBody(formData, len) != len) {parameters.setParseFailedReason(FailReason.REQUEST_BODY_INCOMPLETE);return;}} catch (IOException var19) {Context context = this.getContext();if (context != null && context.getLogger().isDebugEnabled()) {context.getLogger().debug(sm.getString("coyoteRequest.parseParameters"), var19);}parameters.setParseFailedReason(FailReason.CLIENT_DISCONNECT);return;}// 处理POST请求参数,把它放到requestparameter map中(即request.getParameterMap获取到的Map,request.getParameter(name)也是从这个Map中获取的)parameters.processParameters(formData, 0, len);}success = true;return;}success = true;} finally {if (!success) {parameters.setParseFailedReason(FailReason.UNKNOWN);}}}

这篇关于Get和Post各种编码方式和获取参数的问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/688164

相关文章

线上Java OOM问题定位与解决方案超详细解析

《线上JavaOOM问题定位与解决方案超详细解析》OOM是JVM抛出的错误,表示内存分配失败,:本文主要介绍线上JavaOOM问题定位与解决方案的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录一、OOM问题核心认知1.1 OOM定义与技术定位1.2 OOM常见类型及技术特征二、OOM问题定位工具

python获取指定名字的程序的文件路径的两种方法

《python获取指定名字的程序的文件路径的两种方法》本文主要介绍了python获取指定名字的程序的文件路径的两种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要... 最近在做项目,需要用到给定一个程序名字就可以自动获取到这个程序在Windows系统下的绝对路径,以下

Vue3绑定props默认值问题

《Vue3绑定props默认值问题》使用Vue3的defineProps配合TypeScript的interface定义props类型,并通过withDefaults设置默认值,使组件能安全访问传入的... 目录前言步骤步骤1:使用 defineProps 定义 Props步骤2:设置默认值总结前言使用T

SpringBoot 获取请求参数的常用注解及用法

《SpringBoot获取请求参数的常用注解及用法》SpringBoot通过@RequestParam、@PathVariable等注解支持从HTTP请求中获取参数,涵盖查询、路径、请求体、头、C... 目录SpringBoot 提供了多种注解来方便地从 HTTP 请求中获取参数以下是主要的注解及其用法:1

HTTP 与 SpringBoot 参数提交与接收协议方式

《HTTP与SpringBoot参数提交与接收协议方式》HTTP参数提交方式包括URL查询、表单、JSON/XML、路径变量、头部、Cookie、GraphQL、WebSocket和SSE,依据... 目录HTTP 协议支持多种参数提交方式,主要取决于请求方法(Method)和内容类型(Content-Ty

Web服务器-Nginx-高并发问题

《Web服务器-Nginx-高并发问题》Nginx通过事件驱动、I/O多路复用和异步非阻塞技术高效处理高并发,结合动静分离和限流策略,提升性能与稳定性... 目录前言一、架构1. 原生多进程架构2. 事件驱动模型3. IO多路复用4. 异步非阻塞 I/O5. Nginx高并发配置实战二、动静分离1. 职责2

解决升级JDK报错:module java.base does not“opens java.lang.reflect“to unnamed module问题

《解决升级JDK报错:modulejava.basedoesnot“opensjava.lang.reflect“tounnamedmodule问题》SpringBoot启动错误源于Jav... 目录问题描述原因分析解决方案总结问题描述启动sprintboot时报以下错误原因分析编程异js常是由Ja

MySQL 表空却 ibd 文件过大的问题及解决方法

《MySQL表空却ibd文件过大的问题及解决方法》本文给大家介绍MySQL表空却ibd文件过大的问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考... 目录一、问题背景:表空却 “吃满” 磁盘的怪事二、问题复现:一步步编程还原异常场景1. 准备测试源表与数据

解决Nginx启动报错Job for nginx.service failed because the control process exited with error code问题

《解决Nginx启动报错Jobfornginx.servicefailedbecausethecontrolprocessexitedwitherrorcode问题》Nginx启... 目录一、报错如下二、解决原因三、解决方式总结一、报错如下Job for nginx.service failed bec

python中的显式声明类型参数使用方式

《python中的显式声明类型参数使用方式》文章探讨了Python3.10+版本中类型注解的使用,指出FastAPI官方示例强调显式声明参数类型,通过|操作符替代Union/Optional,可提升代... 目录背景python函数显式声明的类型汇总基本类型集合类型Optional and Union(py