请放心:字符集问题 - 无法识别使用放心传递有效的内容类型,并给出错误,因为内容类型无效

Rest assured: charset issue - Passing valid contentType using rest assured is not recognized and giving error as Content Type is not valid

放心版本:3.0.5

作为用户,我们以下面的格式将 contentType 作为 XML 传递给有效内容。

contentType(ContentType.XML) OR .contentType("application/xml")

在应用程序中允许的内容类型是: "application/xml" 提供的内容类型反映如下。

Content-Type=application/xml; charset=ISO-8859-1

因此出现错误 "Content Type is not valid" 如何处理这个用例。

正如预期的内容类型是 application/xml 但提供的内容类型对象包括 "charset=ISO-8859-1"。因此我们需要删除这个字符集细节。

EncoderConfig encoderconfig = new EncoderConfig();
    Response response = given()
            .config(RestAssured.config()
                    .encoderConfig(encoderConfig().appendDefaultContentCharsetToContentTypeIfUndefined(false)))
            .contentType(ContentType.XML)
            .log().all().body(this.buildPayload()).when().
    post(...).

...;

更多详情请参考以下链接:

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

https://groups.google.com/forum/#!topic/rest-assured/O74EgJWUSJY

尝试下面的一组代码....

given().
        config(RestAssured.config().encoderConfig(encoderConfig().appendDefaultContentCharsetToContentTypeIfUndefined(false))).
        contentType("application/json").
        body(...).
when().
        post(...).
...

如果您使用 RequestSpecBuilder 构建 RequestSpecification,那么您需要在创建最终规范

之前删除 charset=ISO-8859-1
private static RequestSpecification specification;

 
RequestSpecBuilder builder = new RequestSpecBuilder();
         builder.setConfig(RestAssuredConfig.newConfig().encoderConfig(EncoderConfig.encoderConfig().appendDefaultContentCharsetToContentTypeIfUndefined(false)));
builder.setContentType(ContentType.XML);
specification = builder.build();
            
// And then you can use in your code like
             
RestAssured.given().spec(specification).body(XMLrequestBody).when().
      post(...).
EncoderConfig EC= new EncoderConfig();

given().config(RestAssured.config()
        .encoderConfig(EC.appendDefaultContentCharsetToContentTypeIfUndefined(false)))
.contentType(ContentType.XML);