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

问题描述 投票:0回答:1

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

Map<String, Object>  jsonAsMap = new HashMap<>();
    jsonAsMap.put("username", "John");
    jsonAsMap.put("email", "[email protected]");

    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": "[email protected]",
    "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个回答
1
投票

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

您应该避免自动将charset添加到content-type标头:

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

之后我们有:

Content-Type=application/json
© www.soinside.com 2019 - 2024. All rights reserved.