rest - “Application/vnd.api+json”抛出“不支持的媒体类型”
问题描述
我正在使用 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": "xx",
"last_name": "xx",
"email": "xx@gp.com",
"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 库。
解决方案
在日志中,您可以看到“ 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;
推荐阅读
- apache-kafka - Kafka Streams:TimeoutException:60000 毫秒后无法更新元数据
- sql - 查询运行 60+ 分钟,优化提示
- javascript - 如何在 Flutter 中嵌入图书查看器?
- python - ImportError:无法导入名称 as_cuda_ndarray_variable
- javascript - React 中的箭头函数
- office-js - 使用 fetch 方法的自定义函数不起作用
- python - 具有向量输出和 2D 图像图形输入的 CNN(输入是一个数组)
- sql - 计算 Oracle 中每个 ID 列的两个最近日期之间的天数
- postgresql - 如何使用 ssl 身份验证从 FluentNhibernate 连接到 postgres
- python - 在 unittest discover 中输出测试名称