如何使用 hashmap 对象发送 queryParam

How to send queryParam with hashmap object

我试图用 java 在 post 中击中这个 api 并安心。但是 api 有很多 queryParam 的 contentype- application/x-www-form-urlencoded,无法发送手动更改它。

示例代码如下-

RequestSpecification request=given();
        Response responseSample = request
                .queryParam("lastName","Sharma")
                .queryParam("firstName","Sobhit")
                .queryParam("street","523-E-BROADWAY")
                .post(url);

我有多个参数用于添加示例 3。我想从 hashmap 对象中读取它并发送它。

您需要更改代码:

RequestSpecification request=given();

// add the request query param
map.forEach((k, v) -> {request.queryParam(k,v);});

// send the request
Response responseSample = request.post(url);

使用rest-assured v3.0.3我们可以这样做:

// Put the query params in a map.
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.put("lastName","Sharma");
queryParams.put("firstName","Sobhit");
queryParams.put("street","523-E-BROADWAY");

// Pass the map while creating the request object.
RequestSpecification request=RestAssured.given().queryParams(queryParams);
Response responseSample = request.post(url);

Maven 依赖项:

<dependency>
  <groupId>io.rest-assured</groupId>
  <artifactId>rest-assured</artifactId>
  <version>3.0.3</version>
</dependency>

RestAssured API 提供了多种使用 java.util.Map 发送参数的方法。创建新地图并在其中放置您需要的参数:

Map<String, String> params = new HashMap<>();
params.put("param1", "value1");
params.put("param2", "value2");

然后将此地图添加到您的请求规范中:

  1. 表单参数:

    RestAssured.given()
        .formParams(params)
        .when()
        .post("http://www.example.com");
    
  2. 查询参数:

    RestAssured.given()
        .queryParams(params)
        .when()
        .post("http://www.example.com");
    
  3. 路径参数:

    RestAssured.given()
        .pathParams(params)
        .when()
        .post("http://www.example.com/{param1}/{param2}");
    

还有一个通用方法params(parametersMap: Map): RequestSpecification,但它根据请求规范将参数添加为查询或表单参数。