【问题标题】:Error parsing media type 'application/json;encoding=utf8, charset=utf-8'解析媒体类型 'application/json;encoding=utf8, charset=utf-8' 时出错
【发布时间】:2014-04-06 19:17:45
【问题描述】:

我正在使用带有球衣的 DropWizard 来创建一个从服务器接受 JSON 并将其映射到 POJO 的客户端。但是,调用客户端时出现此错误。

java.lang.IllegalArgumentException: Error parsing media type 'application/json;encoding=utf8, charset=utf-8'

我的代码如下:

@Path("/something")
@Produces(MediaType.APPLICATION_JSON)
public class SampleClient {
  final Client client;
  WebResource.Builder builder;

  public SampleClient (Client client) {
    this.client = client;
    this.builder = client.resource("http://localhost/mysample/service").type("application/json");
  }

  @GET
  public MyMapper getSomething() {
   MyMapper result = builder.accept("application/json").get(MyMapper.class);
   return result;
  }
}

我做错了什么?

【问题讨论】:

    标签: java json rest encoding jersey


    【解决方案1】:

    您是否在客户端中生成该标头?

    根据W3C - 4 The Content-Type Header Field Content-type 标头必须具有以下格式:

    Content-Type := type "/" subtype *[";" parameter] 
    

    在哪里

    parameter := attribute "=" value
    

    所以您可以拥有可解析的媒体类型:

    Content-type: application/json; encoding=utf8; charset=utf8
    

    使用分号代替逗号。这并不意味着它是正确的,只是可解析的。尝试改用:

    Content-type: application/json; charset=utf8
    

    如果这是客户端错误,那么您可能需要配置 Accept 标头(并且 Content-type 不是必需的,因为您没有发送任何有效负载)。在不指定字符集的情况下尝试它(如果失败,它将因其他原因而失败)。您可以使用交互式 REST 客户端测试不同的标头和编码,例如 Firefox REST client

    【讨论】:

    • .type(...).accept(...) 更改为application/json; charset=utf8 也没有帮助。顺便说一句,我的客户正在使用此服务:http://opentable.herokuapp.com/api/restaurants?name=taj
    • 我明白了。在内容类型中返回两个参数的是服务器。它适用于 Firefox REST 客户端。我会在这里与另一个客户一起检查。
    • 是的,我在 chrome 上使用 POSTMAN,它也向我显示了数据。但是,由于某种原因,我在 DropWizard/Jersey 中的客户端无法解析它。
    • 您是否也在服务器中生成该数据?
    • 我刚刚注意到 Firefox 测试器会忽略无效的 HTTP 标头,接受 ';' 之后的任何内容这有点误导。
    【解决方案2】:

    基本上你需要去掉 Content-type 字符串中的逗号“,”

    或者,您需要将逗号括在双引号中

    例子

    内容类型:视频/mp4;编解码器="avc1.64001F,mp4a.40.2"

    “编解码器”中的“逗号”必须用双引号括起来

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-20
      • 1970-01-01
      • 2013-05-09
      • 2018-07-24
      • 2017-07-13
      • 2015-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多