如何在 Rest Assured 中传递多个请求标头?


我们可以使用 Rest Assured 在请求中传递多个标头。Web 服务可以在执行服务调用时接受标头作为参数。标头以键值对的形式表示。

在 Rest Assured 中传递多个标头的方法不止一种——

  • 使用 header 方法以键值格式传递。

语法

Response r = given()
.baseUri("https://tutorialspoint.com/")
.header("header1", "value1")
.header("header2", "value2")
.get("/about/about_careers.htm");
  • 使用 headers 方法以 Map 的形式传递。

语法

Map<String,Object> m = new HashMap<String,Object>();
m.put("header1", "value1");
m.put("header2, "value2");
Response r = given()
.baseUri("https://tutorialspoint.com/")
.headers(m)
.get("/about/about_careers.htm");
  • 使用 headers 方法以 List 的形式传递。

语法

List<Header> h = new ArrayList<Header>();
h.add(new Header("header1", "value1"));
h.add(new Header("header2", "value2"));
Response r = given()
.baseUri("https://tutorialspoint.com/")
.headers(h)
.get("/about/about_careers.htm");

示例

代码实现

import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
public class NewTest {
   @Test
   public void addMultipleHeader() {
      String baseUrl =
      "https://api.reverb.com/api/articles?page=1&per_page=24";

      //input details with multiple headers
      RequestSpecification r = RestAssured.given()
      .header("Accept", "application/hal+json")
      .header("Content-Type", "application/json")
      .header("Accept-Version", "3.0");

      //obtain get Response
      Response res = r.get(baseUrl);

      //get status code
      int c = res.getStatusCode();
      System.out.println(c);
   }
}

输出

更新日期: 19-Nov-2021

8 千+ 浏览

开启您的职业生涯

完成课程后获得认证

开始
广告
© . All rights reserved.