如何使用hashmap对象发送queryParam

时间:2019-09-27 08:10:50

标签: java api rest-assured

我试图用Java来发布该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对象中读取并发送它。

3 个答案:

答案 0 :(得分:1)

您需要使用以下代码更改代码:

RequestSpecification request=given();

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

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

答案 1 :(得分:1)

使用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>

答案 2 :(得分:1)

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,但是它会根据请求规范将参数添加为查询或表单参数。