当测试遇到request指定header(疑惑到反思)

it2022-05-09  25

场景描述:

1. (php+nginx)RD提测代码中向后端发起请求时指定header内容,包括useragent/content-type/accept-encoding(原框架中未指定)。

'useragent' => "Mozilla/5.0" 'content-type' => "application/x-www-form-urlencoded" 'Accept-Encoding' => "gzip"

2. 在测试环境测试,能够返回预期的结果;

3. 潜在担心头部指定不当会造成乱码等情况,但不清晰(问题所在,未清晰了解导致未知的敬畏)

解决:

1. 重新理解header中的useragent/content-type/accept-encoding;

根据《HTTP权威指南》附录所述,useragent/content-type/accept-encoding意义如下:

 useragent 定义

             

2. 用途:如服务器可根据发起请求的客户端类型定制化返回结果

3. 所取值的意义:

'useragent' => "Mozilla/5.0"

Mozilla/5.0 is the general token that says the browser is Mozilla compatible, and is common to almost every browser today.(参考:useragent)

content-type

1. 定义

2. 用途:内容协商头部集。如浏览器收到服务端的返回,即可知道如何展示;但其实现有场景是客户端头部中的header,表单的提交流程如下(参考:form)。

其中与content-type相关的就是user agent会根据enctype值encode表单元素。

3. 所取值的意义:

'content-type' => "application/x-www-form-urlencoded"

 当以上所说的表单元素enctype未指定时,会采用默认content-type值,即为application/x-www-form-urlencoded。

accept-encoding

1.定义

2.用途:内容协商头部集。

3. 所取值意义:压缩算法

'Accept-Encoding' => "gzip"

2.header未指定时useragent/content-type/accept-encoding使用的是什么值?

实质:HTTP内容协商机制nginx.conf中http部分指定头部字段赋值规则(以下以nginx官网代码为例) user www www; ## Default: nobody worker_processes 5; ## Default: 1 error_log logs/error.log; pid logs/nginx.pid; worker_rlimit_nofile 8192; events { worker_connections 4096; ## Default: 1024 } http { include conf/mime.types; ##指定content-type include /etc/nginx/proxy.conf; include /etc/nginx/fastcgi.conf; index index.html index.htm index.php; default_type application/octet-stream; #默认类型,无类型,字节流 ...... } content-type由其中的引入的mime.types文件指定(相对路径基于webserver目录),根据文件后缀名指定content-type。(参考:MIME与mime.type) types { text/html html htm shtml; text/css css; text/xml xml rss; image/gif gif; image/jpeg jpeg jpg; application/x-javascript js; text/plain txt; text/x-component htc; text/mathml mml; image/png png; image/x-icon ico; image/x-jng jng; image/vnd.wap.wbmp wbmp; ...... } gzip压缩也可在nginx中配置开启(参考:ngx_http_gzip模块) http { ...... gzip on; gzip_min_length 1000; gzip_proxied expired no-cache no-store private auth; gzip_types text/plain application/xml; ......}

3. header未指定时(原框架)和指定时(现代码)有什么区别(服务端处理和客户端接收)

看到这里,回归场景,这些头部主要用于实现内容协商(Chapter 17 HTTP权威指南),是否指定的区别需要确认服务器是否实现了内容协商机制,及其nginx配置。

另外,测试环境和线上环境配置可能存在差异,最终后续是移除了header赋值相关代码。

转载于:https://www.cnblogs.com/matric/p/6687455.html


最新回复(0)