REST Assured 50 - How To Set Content-Type For Request In Rest Assured

REST Assured 系列汇总 之 REST Assured 50 - How To Set Content-Type For Request In Rest Assured

介绍

Content-Type header 是指媒体类型 或 MIME( Multipurpose Internet Mail Extensions ) 或 文件类型。当发起任何 POST 或 PUT 请求时,我们可能需要传一个 payload。payload 可能是 API 支持的任意格式,如 XML, JSON 等。我们需要用到 Content-Type header 让服务器知道一个请求中 payload 的格式。

同样,response 中的 Content-Type header 是指 response 返回的格式。request 中的 Content-Type header 和 response 中的 Content-Type header 不是强制必须一样的。

前提条件

添加 REST Assured 依赖包

 <!-- REST Assured -->
  <dependency>
     <groupId>io.rest-assured</groupId>
     <artifactId>rest-assured</artifactId>
     <version>4.4.0</version>
  </dependency>

什么要显示地为request设置 Content-Type header

Postman 工具会根据 所选 request body 格式自动添加 Content-Type header。例如,如果选择 request body 格式为 JSON,那么 Postman 会自动添加名为 “Content-Type” ,值为“application/json“ 的 header。而 REST Assured 是不会自动添加合适的 Content-Type heade的,这样可能会得到一个不是预期的 response,因为 server 端不能识别出 payload 的格式。

下面我们通过一个例子,不设置 Content-Type header,传入一个 JSON 格式的 payload。

import org.junit.Test;
 
import io.restassured.RestAssured;
 
public class SetContentTypeForRequest {
    
    
	
	@Test
	public void WIthoutSettingContentType()
	{
    
    
		RestAssured
		.given()
		.log()
		.all()
		.body("{\r\n" + 
				"    \"firstname\" : \"Jim\",\r\n" + 
				"    \"lastname\" : \"Brown\",\r\n" + 
				"    \"totalprice\" : 111,\r\n" + 
				"    \"depositpaid\" : true,\r\n" + 
				"    \"bookingdates\" : {\r\n" + 
				"        \"checkin\" : \"2018-01-01\",\r\n" + 
				"        \"checkout\" : \"2019-01-01\"\r\n" + 
				"    },\r\n" + 
				"    \"additionalneeds\" : \"Breakfast\"\r\n" + 
				"}")
		.post("https://restful-booker.herokuapp.com/booking")
		.then()
		.log()
		.all();
	}
 
}

输出:

Request method:	POST
Request URI:	https://restful-booker.herokuapp.com/booking
Proxy:			<none>
Request params:	<none>
Query params:	<none>
Form params:	<none>
Path params:	<none>
Headers:		Accept=*/*
				Content-Type=text/plain; charset=ISO-8859-1
Cookies:		<none>
Multiparts:		<none>
Body:
{
    "firstname" : "Jim",
    "lastname" : "Brown",
    "totalprice" : 111,
    "depositpaid" : true,
    "bookingdates" : {
        "checkin" : "2018-01-01",
        "checkout" : "2019-01-01"
    },
    "additionalneeds" : "Breakfast"
}
HTTP/1.1 500 Internal Server Error
Server: Cowboy
Connection: keep-alive
X-Powered-By: Express
Content-Type: text/plain; charset=utf-8
Content-Length: 21
Etag: W/"15-/6VXivhc2MKdLfIkLcUE47K6aH0"
Date: Sat, 25 Sep 2021 11:14:56 GMT
Via: 1.1 vegur

Internal Server Error

我们在 request 中传的是一个 JSON payload,但输出中 request 的 Content-Type header 的值是 “text/plain”, 响应返回了 “Internal server error“。Server 不能理解 request payload的正确格式,所以失败。这就是我们应该为一个 request 设置一个合适的 Content-Type 的原因。

设置 request Content-Type header

因为 Content-Type 是一个 header,我们可以通过前面介绍的方法以键值对的形式传递。

import org.junit.Test;
 
import io.restassured.RestAssured;
 
public class SetContentTypeForRequest {
    
    
	
	@Test
	public void settingContentTypeAsHeader()
	{
    
    
		RestAssured
		.given()
		.log()
		.all()
		.header("Content-Type", "application/json")
		.body("{\r\n" + 
				"    \"firstname\" : \"Jim\",\r\n" + 
				"    \"lastname\" : \"Brown\",\r\n" + 
				"    \"totalprice\" : 111,\r\n" + 
				"    \"depositpaid\" : true,\r\n" + 
				"    \"bookingdates\" : {\r\n" + 
				"        \"checkin\" : \"2018-01-01\",\r\n" + 
				"        \"checkout\" : \"2019-01-01\"\r\n" + 
				"    },\r\n" + 
				"    \"additionalneeds\" : \"Breakfast\"\r\n" + 
				"}")
		.post("https://restful-booker.herokuapp.com/booking")
		.then()
		.log()
		.all();
	}
 
}

输出:

Request method:	POST
Request URI:	https://restful-booker.herokuapp.com/booking
Proxy:			<none>
Request params:	<none>
Query params:	<none>
Form params:	<none>
Path params:	<none>
Headers:		Accept=*/*
				Content-Type=application/json
Cookies:		<none>
Multiparts:		<none>
Body:
{
    "firstname": "Jim",
    "lastname": "Brown",
    "totalprice": 111,
    "depositpaid": true,
    "bookingdates": {
        "checkin": "2018-01-01",
        "checkout": "2019-01-01"
    },
    "additionalneeds": "Breakfast"
}
HTTP/1.1 200 OK
Server: Cowboy
Connection: keep-alive
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 195
Etag: W/"c3-AjbAZNa7Ods9W5ziFxGgv2BnFnc"
Date: Sat, 25 Sep 2021 11:27:33 GMT
Via: 1.1 vegur

{
    "bookingid": 27,
    "booking": {
        "firstname": "Jim",
        "lastname": "Brown",
        "totalprice": 111,
        "depositpaid": true,
        "bookingdates": {
            "checkin": "2018-01-01",
            "checkout": "2019-01-01"
        },
        "additionalneeds": "Breakfast"
    }
}

上面的方式,如果将 header 名和值拼写错误,将不会得到预期的响应。为了克服这种人为失误,RequestSpecification 类提供了下面的方法:

RequestSpecification contentType(ContentType contentType);

ContentType 是一个枚举类型,其值包含 “ANY”, “JSON”, “XML” 等。如果你想设置 Content-Type 为 JSON,可以这样:

contentType(ContentType.JSON)

代码:

import org.testng.annotations.Test;
 
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
 
public class SetContentTypeForRequest {
    
    
	
	@Test
	public void settingContentTypeAsContentType()
	{
    
    
		RestAssured
		.given()
		.log()
		.all()
		.contentType(ContentType.JSON)
		.body("{\r\n" + 
				"    \"firstname\" : \"Jim\",\r\n" + 
				"    \"lastname\" : \"Brown\",\r\n" + 
				"    \"totalprice\" : 111,\r\n" + 
				"    \"depositpaid\" : true,\r\n" + 
				"    \"bookingdates\" : {\r\n" + 
				"        \"checkin\" : \"2018-01-01\",\r\n" + 
				"        \"checkout\" : \"2019-01-01\"\r\n" + 
				"    },\r\n" + 
				"    \"additionalneeds\" : \"Breakfast\"\r\n" + 
				"}")
		.post("https://restful-booker.herokuapp.com/booking")
		.then()
		.log()
		.all();
	}
 
}

输出:

Request method:	POST
Request URI:	https://restful-booker.herokuapp.com/booking
Proxy:			<none>
Request params:	<none>
Query params:	<none>
Form params:	<none>
Path params:	<none>
Headers:		Accept=*/*
				Content-Type=application/json
Cookies:		<none>
Multiparts:		<none>
Body:
{
    "firstname": "Jim",
    "lastname": "Brown",
    "totalprice": 111,
    "depositpaid": true,
    "bookingdates": {
        "checkin": "2018-01-01",
        "checkout": "2019-01-01"
    },
    "additionalneeds": "Breakfast"
}
HTTP/1.1 200 OK
Server: Cowboy
Connection: keep-alive
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 195
Etag: W/"c3-AjbAZNa7Ods9W5ziFxGgv2BnFnc"
Date: Sat, 25 Sep 2021 11:27:33 GMT
Via: 1.1 vegur

{
    "bookingid": 27,
    "booking": {
        "firstname": "Jim",
        "lastname": "Brown",
        "totalprice": 111,
        "depositpaid": true,
        "bookingdates": {
            "checkin": "2018-01-01",
            "checkout": "2019-01-01"
        },
        "additionalneeds": "Breakfast"
    }
}

Guess you like

Origin blog.csdn.net/wumingxiaoyao/article/details/120473497