我一直在尝试使用resttemplate或Restassured库来自动化一些API测试,但是在发布请求时遇到了问题。我似乎无法弄清楚该如何处理。我不断收到415不支持的类型错误,我已经尝试了许多想法并读取了数百个线程。如果有人有解决方案,请告诉我。这是开发人员代码
@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字符串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的信息>