在接口测试中,接口通常是GET请求或者POST请求。以下是对接口测试中常见的四种Post请求数据方式进行一个详细的讲解:
一、post请求主体详解
一个正常的post请求主要包括请求行,请求头,请求主体。
对于get请求来说没有请求主体entity-body。对于post请求而言,不会对发送请求的数据格式进行限制,理论上你可以发任意数据,但是服务器能不能处理就是另一回事了。服务器收到数据后,如何解析数据呢?它会以请求头中的Content-Type设置的内容来进行数据解析。确定好Content-Type的格式之后,请求主体的数据格式也就确定下来了。
二、Content-Type的格式有四种:application/x-www-form-urlencoded(这也是默认格式)
application/json
text/xml
multipart/form-data
这些不同的post请求数据格式要通过HttpEntity来构造,有必要简单理一下HttpClient的HttpEntity对象,因为所有的post请求数据均需要置于HttpEntity实体中进行发送。HttpEntity是一个接口,实现这个接口的具体类有很多,比较常用的是StringEntity、UrlEncodedFormEntity(继承自StringEntity)、MultipartEntity。他们将在发送不同格式的post请求时被用到。接下来就详细地介绍每一种数据格式对应的fiddler请求模拟和Requests请求模拟(Python实现)的实现情况。
三、application/x-www-form-urlencoded数据格式
在W3C官网上明确对这种数据格式进行了定义:This is the default content type. Forms submitted with this content type must be encoded as follows:Control names and
values are escaped. Space characters are replaced by '+', and then reserved characters are escaped as described in
[RFC1738], section 2.2: Non-alphanumeric characters are repla