簡體   English   中英

如何在 POST 請求中發送數組 rest 放心

[英]how to send an array in POST request rest assured

尋找一種在 post 請求中發送數組的方法,它在 postman 上工作,但我不能對 rest 中的 java 中的保證庫執行相同的操作,在此處輸入圖像描述我嘗試創建一個 Map<String,Object> 變量並發送它但它也沒有用

你怎么能保證發送一個 rest 的數組呢?

添加部分代碼enter image description here

在此處輸入圖像描述

到目前為止,我將 JSONobject 一個嵌套到另一個中以發送請求並且它確實有效,直到我不得不為數據/步驟/數據參數發送一個數組

基本上有兩種主要方法。 將其作為字符串發送或使用 Gson 等庫將其從 DTO/POJO 序列化為 json 字符串。如果要發送原始字符串,則必須轉義 json 中的引號,例如:

static String json = "{\"id\": 110, \"product\": \"Beer\",\"price\": 1900}";

如果你想使用 DTO/POJO 方法,你必須像這樣創建 object:

public class Product {
    public Product(Integer id, String product, Double price) {
        this.id = id;
        this.product = product;
        this.price = price;
    }

    private Integer id;
    private String product;
    private Double price;
}

完整示例:

public class Test {
    static Gson gson = new GsonBuilder().setPrettyPrinting().create();
    static String json = "{\"id\": 110, \"product\": \"Beer\",\"price\": 1900}";

    public static void main(String[] args) {
        //Setting default rest assured url/base path
        RestAssured.baseURI = "https://google.com";
        RestAssured.basePath = "/v1";

        //With escaped string
        RestAssured.given()
                .log().all()
                .body(json).when().post("endpoint");

        //Creating dto
        Product beer = new Product(121212, "Beer", 10.50);
        RestAssured.given()
                .log().all()
                .body(gson.toJson(beer)).when().post("endpoint");

    }


}

控制台 output:

Request method: POST
Request URI:    https://google.com/v1/endpoint
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:
{"id": 110, "product": "Beer","price": 1900}



Request method: POST
Request URI:    https://google.com/v1/endpoint
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:
{
  "id": 121212,
  "product": "Beer",
  "price": 10.5
}

內容類型應與有效負載相匹配,例如:

   RestAssured.given()
                .contentType(ContentType.JSON)
                .log().all()
                .body(gson.toJson(beer)).when().post("endpoint");

您可以對 DTO 中的數組使用 List 或 List。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM