Java 解析媒体类型 'application/json;encoding=utf8, charset=utf-8' 时出错

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22185776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 14:11:14  来源:igfitidea点击:

Error parsing media type 'application/json;encoding=utf8, charset=utf-8'

javajsonrestencodingjersey

提问by Anthony

I'm using DropWizard with jersey to make a client that accepts JSON from a server and maps it to a POJO. However, I get this error when invoking the client.

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

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

My code is as follows:

我的代码如下:

@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;
  }
}

What am I doing wrong?

我究竟做错了什么?

采纳答案by helderdarocha

Are you generating that header in your client?

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

According to W3C - 4 The Content-Type Header Fieldthe Content-typeheader must have the format:

根据W3C - 4 内容类型标题字段Content-type标题必须具有以下格式:

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

where

在哪里

parameter := attribute "=" value

So you couldhave as a parseable media type:

所以你可以有一个可解析的媒体类型:

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

Using a semicolon instead of a comma. This doesn't mean it's correct, just parseable. Try using instead:

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

Content-type: application/json; charset=utf8

If that's a client error, then you might need to configure an Acceptheader (and the Content-type is not necessary since you aren't sending any payload). Try it without specifying the charset (if it fails, it will fail for another reason). You can test different headers and encodings using an interactive REST client, such as the Firefox REST client

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

回答by Henry

Basically you need to remove the comma "," in the Content-type string

基本上你需要删除内容类型字符串中的逗号“,”

Or, you need to wrap the comma in double quotes

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

example

例子

Content-type: video/mp4; codecs="avc1.64001F,mp4a.40.2"

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

the "comma" in "codecs" has to be wrapped in double-quotes

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