【问题标题】:Send JSON body using Rest Assured, but server ignores it使用 Rest Assured 发送 JSON 正文,但服务器忽略它
【发布时间】:2019-03-05 11:09:46
【问题描述】:

我在使用 RestAssered 时遇到了困难。我的目标是为创建用户发送 POST 请求。我是怎么做的(来自文档https://github.com/rest-assured/rest-assured/wiki/Usage):

Map<String, Object>  jsonAsMap = new HashMap<>();
    jsonAsMap.put("username", "John");
    jsonAsMap.put("email", "testkdd@test.test");

    response = restAssured.given()
            .contentType(JSON)
            .header("Authorization", db.getAuthToken())
            .body(jsonAsMap)
            .when()
            .log().all()
            .post(apiCreateManager_POST);
    response.then().log().all();

请求:

Request method: POST
Request URI:    https://myapplication/api/v1/manager/managers
Proxy:          <none>
Request params: <none>
Query params:   <none>
Form params:    <none>
Path params:    <none>
Headers:        Authorization=Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXU....
                Accept=*/*
                Content-Type=application/json; charset=UTF-8
Cookies:        <none>
Multiparts:     <none>
Body:
{
    "email": "testkdd@test.test",
    "username": "John"
}

回复:

HTTP/1.1 422 Unprocessable Entity
Server: nginx/1.12.0
Date: Tue, 05 Mar 2019 10:52:54 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
X-Powered-By: PHP/7.1.20-1+ubuntu16.04.1+deb.sury.org+1
Cache-Control: private, must-revalidate
pragma: no-cache
expires: -1

{
    "errors": {
        "username": [
            "This value should not be null.",
            "This value should not be blank."
        ],
        "email": [
            "This value should not be blank."       
        ]
    }
}

服务器没有看到我的 JSON 参数。 我使用 Postman 检查了服务器,一切正常。

【问题讨论】:

    标签: json rest-assured


    【解决方案1】:

    我找到了解决方案! 问题出在 Content-Type=application/json; charset=UTF-8

    您应该避免将字符集自动添加到内容类型标题中:

    RestAssured.config = RestAssured.config().encoderConfig(encoderConfig().appendDefaultContentCharsetToContentTypeIfUndefined(false));
    

    然后我们有:

    Content-Type=application/json
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多