automated-tests - 如何在 Rest aussured pf RestTemplate 中添加标题
问题描述
我一直在尝试使用 resttemplate 或 Restassured 库来自动化一些 API 测试,但我在发布请求时遇到了问题。我似乎无法弄清楚如何处理这个问题。我不断收到 415 unsupported type error ,我已经尝试了很多想法并阅读了数百个线程。如果有人有解决方案,请告诉我。这是开发者代码
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public Response postData(@FormDataParam("file") InputStream is,
@FormDataParam("file") FormDataContentDisposition fileName,
@FormDataParam("checkInCommInfoInput") String checkInCommInfoInput,
@HeaderParam("authorization") String authString) { }
这就是我尝试使用 resttemplate String addURI = " https://myURI "; HttpHeaders 标头 = 新的 HttpHeaders();
//headers.add("Accept","*/*");
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", " a values will be here ");
System.out.println("**************************"+headers.getContentType());
String jsonBody = "my json file will be here";
//System.out.println("\n\n" + jsonBody);
HttpEntity<String> entity = new HttpEntity<String>(jsonBody, headers);
//POST Method to Add New Employee
response = this.restTemplate.postForEntity(addURI, entity, String.class);
responseBodyPOST = response.getBody();
// Write response to file
responseBody = response.getBody().toString();
我对 RestAssured 的尝试
RestAssured.useRelaxedHTTPSValidation();
RestAssured.baseURI ="https://myURI";
EncoderConfig encoderconfig = new EncoderConfig();
Response response = RestAssured.given()
.header("Content-Type","application/json" )
.header("Authorization", "a vvalues will be here")
.header("Accept",ContentType.JSON )
.config(RestAssured.config()
.encoderConfig(encoderconfig.appendDefaultContentCharsetToContentTypeIfUndefined(false)))
//.contentType(ContentType.JSON)
// .accept("application/json")
.log().all().body(jsonBody).post()
.then()
.assertThat()
.log().ifError()
.statusCode(200)
.extract().response();
System.out.println("-------------"+ response.getBody().asString());
解决方案
API 正在测试@Consumes(MediaType.MULTIPART_FORM_DATA)
,但测试发送内容.header("Content-Type","application/json" )
415 错误,正如您已经明确提到unsupported type error
的,测试客户端发送的正文内容与 API 接受的内容之间存在内容类型不匹配。
请参阅此博文:https ://blog.jayway.com/2011/09/15/multipart-form-data-file-uploading-made-simple-with-rest-assured/关于如何发送 MULTIPART_FORM_DATA
推荐阅读
- python-3.x - 模拟行星绕太阳运行的轨迹。椭圆没有闭合
- javascript - 如何使用 webpack 为数组类型添加新功能
- javascript - 在用户键入时更新 contentEditable 字段中的文本
- c# - 如何使用订单号 WPF 调整 DataGrid 列?
- powerbi - 过滤汇总列
- vue.js - Vuetify Datatable - 仅在第一行渲染元素
- azure-devops - Azure DevOps:使用不同的运行设置在代理池中的代理上并行运行测试
- r - 使用 R 生成 Excel 样式的组合图 - 用于 x 轴上的分类数据
- c# - ASP.NET Identity 返回元数据资源错误
- memcached - Memcached 的反应式客户端