有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

获得“java.lang.IllegalArgumentException:不知道如何将XXX编码为字节流”时请放心

我想从字符串中提取JSON数据。这是我的密码:

String APIBody = "{\"queryString\": \"Pearson AND unscrubbed:false\"}";
RequestSpecBuilder rbuild = new RequestSpecBuilder();
rbuild.setBody(APIBody);
rbuild.setContentType("application json;charset = UTF-8");
RequestSpecification rSpec = rbuild.build();
Response resp = given().headers(headers).spec(rSpec).when().post("https://content-service.stg-prsn.com/csg/api/v2/search");

在最后一行中,我将作为hashmap传递多个头

我得到以下错误:

java.lang.IllegalArgumentException: Don't know how to encode {"queryString": "Pearson AND unscrubbed:false"} as a byte stream.

Please use EncoderConfig (EncoderConfig#encodeContentTypeAs) to specify how to serialize data for this content-type.
For example: "given().config(RestAssured.config().encoderConfig(encoderConfig().encodeContentTypeAs("application json", ContentType.TEXT))). .."
  at com.jayway.restassured.internal.http.EncoderRegistry.encodeStream(EncoderRegistry.java:129)

共 (3) 个答案

  1. # 1 楼答案

    尝试使用javajson.jar而不是restassured。我尝试使用下面给出的restassuredapi:

    Response resp = given().config(RestAssured.config().encoderConfig(((Object) encoderConfig()).encodeContentTypeAs("application json", APIBody)));
    

    但是jar文件中缺少/未定义以下方法 配置:

    The method config() is undefined for the type RestAssured encodeContentTypeAs

    The method encodeContentTypeAs(String, String) is undefined for the type Object

  2. # 2 楼答案

    我觉得restassed不够聪明,无法理解带有字符集的内容类型JSON。简单的解决办法是更换

    setContentType("application json;charset = UTF-8");
    

    使用enumio。重新发行。http。ContentType

    setContentType(ContentType.JSON)
    
  3. # 3 楼答案

    试着用下面的方式给予

    Response res = given()
                    .relaxedHTTPSValidation()
                    .body(APIBody)
                    .with()
                    .contentType("application/json")
                    .then()
                    .post(url);
    

    谢谢