简体   繁体   中英

Getting 200 in postman but 400 in Rest assured post method

I make similar request with postman and rest-assured with the same credentials and receiving different status codes. The only header which accept server is application/json. Data and url are similar. I tried to add headers from postman, but it failed. ResstAssured.auth() isn't fit for me. Maybe someone have solution or faced this problem.

Code example:

public Response userLogin() {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("password", "pass");
            jsonObject.put("account_name", "name");
            jsonObject.put("email", "mail");
            jsonObject.put("mfa_otp", 123456);
            String url = "url";
            return given()
                    .contentType(ContentType.JSON)
                    .body(jsonObject.toString())
                .when()
                    .post(url)
                .then()
                    .statusCode(200)
                    .extract()
                    .response();
        }

Request:

Request method: POST
Request URI:    url
Proxy:          <none>
Request params: <none>
Query params:   <none>
Form params:    <none>
Path params:    <none>
Content-Type=application/json; charset=UTF-8
Cookies:        <none>
Multiparts:     <none>

    Body:

{
        "password": "pass",
        "account_name": "name",
        "email": "mail"
}

Response:

HTTP/1.1 400 Bad Request
Date: Tue, 13 Apr 2021 19:27:16 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Server: nginx
X-Content-Type-Options: nosniff
X-Frame-Options: deny
Cache-Control: no-cache, no-store, must-revalidate
Access-Control-Allow-Origin: *
Access-Control-Expose-Headers: ETag, Link, X-Request-Id
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
X-Request-Id: 4e74caf3fa982d27cb827b5f7ebf6942
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload

{
    "status": "Bad Request",
    "message": "Missing required parameter.",
    "errors": [
        {
            "code": "required",
            "field": "account_name"
        }
    ]
}

Postman:

邮递员请求正文

邮递员内容类型

标头

I figured out why It's happening every time, the Rest assured by default adding UTF-8 charset to content type.

Add this code to rest assured config method and you will be just fine, hope it will help to you.

private RestAssuredConfig decodeCharset = config().encoderConfig(encoderConfig().appendDefaultContentCharsetToContentTypeIfUndefined(false));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM