HttpMessageConverter<T> 是自动转换还是我们需要在 Spring 中指定

Does HttpMessageConverter<T> converts automatically or do we need to specify in Spring

我正在 Spring java 中工作 我遇到了 HttpMessageConverter 用于将响应类型转换为其他类型

我想知道一些关于这个的事情class这里有一个例子

有一个服务器和一个客户端,服务器以某种格式发送响应(比如 XML),如果客户端发送像

headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

HttpMessageConverter 会自动将响应类型转换为 Json 还是在客户端代码中我们需要说 HttpMessageConverter 来转换响应类型

Server sends response in some format (say XML) and client wants the response in other format (say Json) if client sends in headers like

有一个概念叫Content Negotiation,简称Conneg。作为客户端,您使用 AcceptAccept-LanguageAccept-Encoding 等 HTTP header 指定您期望的内容类型、语言、编码等,并将该请求发送到服务器和服务器相应地响应。因此,如果您将 Accept header 设置为 application/json 并且服务器 只有 可以提供 application/xml 内容类型,它将 return 406 Not Acceptable HTTP 客户端错误。 基本上它说我可能有你想要的资源,但没有请求的表示

如果您有权访问服务器代码,则可以通过 spring 将它们转换为 xmljson 的方式更改您的 Data Transfer Object。简单地当你用@ResponseBody注释每个方法时,该方法的return值可以默认转换为HttpMessageConverters:

You convert the request body to the method argument by using an HttpMessageConverter. HttpMessageConverter is responsible for converting from the HTTP request message to an object and converting from an object to the HTTP response body. The RequestMappingHandlerAdapter supports the @RequestBody annotation with the following default HttpMessageConverters:

  • ByteArrayHttpMessageConverter converts byte arrays.
  • StringHttpMessageConverter converts strings.
  • FormHttpMessageConverter converts form data to/from a MultiValueMap.
  • SourceHttpMessageConverter converts to/from a javax.xml.transform.Source

此外,如果您将 Jackson 2 库添加到您的类路径,MappingJackson2HttpMessageConverter 将负责转换 to/from JSON.

但是,如果您无法访问服务器代码并且服务器仅提供 XML,唯一的选择是从服务器获取 XML 并手动将其转换为 JSON .