使用Rest Assured发送JSON正文,但服务器将其忽略

时间:2019-03-05 11:09:47

标签: json rest-assured

使用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检查服务器,一切正常。

1 个答案:

答案 0 :(得分:1)

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

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

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

在那之后,我们有了:

Content-Type=application/json