如何在 Rest Assured 中在请求中传递多个标头?
rest assureddynamic programmingprogramming更新于 2025/4/5 8:52:17
在 Rest Assured 中,我们可以在请求中传递多个标头。Web 服务在进行服务调用时可以接受标头作为参数。标头以键值对的形式表示。
在 Rest Assured − 中,有多种传递多个标头的方法。
使用 header 方法以键值格式传递标头。
语法
Response r = given() .baseUri("https://www.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://www.tutorialspoint.com/") .headers(m) .get("/about/about_careers.htm");
使用 headers 方法将它们作为列表传递。
语法
List<Header> h = new ArrayList<Header>(); h.add(new Header("header1", "value1")); h.add(new Header("header2", "value2")); Response r = given() .baseUri("https://www.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"; //输入包含多个标头的详细信息 RequestSpecification r = RestAssured.given() .header("Accept","application/hal+json"); .header("Content-Type","application/json"); .header("Accept-Version","3.0"); //获取 get Response Response res = r.get(baseUrl); //获取状态码 int c = res.getStatusCode(); System.out.println(c); } }