“ Application / vnd.api + json”抛出“不支持的媒体类型”

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

我正在使用Rest Assured为POST调用自动化API,对于Content-Type和ACCEPT标头,我必须使用“ application / vnd.api + json”。但是每次我使用“ application / vnd.api + json”时,我都会得到415状态代码。尽管使用Postman进行相同的POST调用非常正常。

这是我的示例代码:

    ApiUtils.setBaseURI("xxxxx"); 
            ApiUtils.setBasePath("/orders"); 
            RequestSpecification request = RestAssured.given().auth().oauth2(BaseClass.token);
            request.header("ACCEPT", "application/vnd.api+json");
            request.header("Content-Type", "application/vnd.api+json");
            request.body(JsonCreator.createJson());
            Response response = request.post();

下面是收到的回复

Request method: POST
Request URI:    https://xxxxxx/orders

Headers:        ACCEPT=application/vnd.api+json
                Content-Type=application/vnd.api+json; charset=ISO-8859-1
Cookies:        <none>
Multiparts:     <none>
Body:
{
    "data": {
        "type": "orders",
        "attributes": {
            "external_id": "2020-04-04-172",
            "order_items": [
                {
                    "menu_item_id": "5d29ae25805aaf0009095410",
                    "variation_id": "5d29ae25805aaf0009095418",
                    "quantity": 1,
                    "note": "some note"
                }
            ],
            "revenue_center_id": "5d7b44021a2976000938da62",
            "order_type_id": "5d27329790a5ba0009386a75",
            "guests": [
                {
                    "first_name": "Govind",
                    "last_name": "Patil",
                    "email": "[email protected]",
                    "phone": "5551234567"
                }
            ],
            "tip_amount": "1.00"
        }
    }
}

{"errors":[{"status":415,"code":415,"title":"Content-Type must be JSON API-compliant"}],"jsonapi":{"version":"1.0"}}

我尝试按照其他帖子/评论的建议将Content-Type更改为application / json,但这似乎对我的资源不正确。

[当前,我正在使用Rest Assured v4.3.0和json-path v4.3.0。另外,为了构建请求主体,我正在使用com.google.gson.JsonObject库。

rest rest-assured rest-assured-jsonpath
1个回答
1
投票

在日志中,您可以看到正在发送“ charset = ISO-8859-1”,这是由Rest Assured自动添加的,.config()禁用了该功能,并且不发送字符集。

尝试以下内容

ApiUtils.setBaseURI("orders");
ApiUtils.setBasePath("/orders");
RequestSpecification request = RestAssured.given().auth().oauth2(BaseClass.token).header("Content-Type", "application/vnd.api+json").header("Accept", "application/vnd.api+json").config(RestAssured.config().encoderConfig(encoderConfig().appendDefaultContentCharsetToContentTypeIfUndefined(false))).log().all();
request.body(JsonCreator.createJson());
Response response = request.post();

这也需要静态导入

导入静态io.restassured.config.EncoderConfig.encoderConfig;

https://github.com/rest-assured/rest-assured/wiki/Usage#avoid-adding-the-charset-to-content-type-header-automatically

© www.soinside.com 2019 - 2024. All rights reserved.