【问题标题】:Jersey 415 Unsupported Media TypeJersey 415 不支持的媒体类型
【发布时间】:2015-08-21 22:05:35
【问题描述】:

我从几个小时以来一直在尝试纠正 http 错误 415 Unsupported Media Type,但它仍然显示媒体不支持的页面。 我在 Postman 中添加标题 application/json

这是我的 Java 代码

package lostLove;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;  
import javax.ws.rs.POST;
import javax.ws.rs.Path;  
import javax.ws.rs.PathParam;  
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; 

import org.json.JSONObject;


@Path("/Story") 
public class Story {

      @POST
      @Consumes({"application/json"})
      @Produces(MediaType.APPLICATION_JSON)
    //  @Consumes(MediaType.APPLICATION_JSON)
    //  @Path("/Story") 
      public JSONObject sayJsonTextHello(JSONObject inputJsonObj) throws Exception {

        String input = (String) inputJsonObj.get("input");
        String output = "The input you sent is :" + input;
        JSONObject outputJsonObj = new JSONObject();
        outputJsonObj.put("output", output);

        return outputJsonObj;
      }

      @GET  
      @Produces(MediaType.TEXT_PLAIN)  

      public String sayPlainTextHello() {  
        return "hello";
      }

}

这是我的web.xml 文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>LostLove</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
 <servlet>  
    <servlet-name>Jersey REST Service</servlet-name>  
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>  
    <init-param>  
        <param-name>jersey.config.server.provider.packages</param-name>  
        <param-value>lostLove</param-value>  
    </init-param>  
    <load-on-startup>1</load-on-startup>  
  </servlet>  
  <servlet-mapping>  
    <servlet-name>Jersey REST Service</servlet-name>  
    <url-pattern>/rest/*</url-pattern>  
  </servlet-mapping>
</web-app>

【问题讨论】:

    标签: java json rest jersey jax-rs


    【解决方案1】:

    我们的对象如何在响应流和请求流之间进行序列化和反序列化,是通过MessageBodyWritersMessageBodyReaders

    将会发生的情况是,将从提供者的注册表中进行搜索,以查找可以处理JSONObject 和媒体类型application/json 的提供者。如果找不到,则 Jersey 无法处理该请求,并将发送 415 Unsupported Media Type。您通常应该在服务器端也记录一个异常。不确定您是否有机会查看日志。

    Jersey 没有任何用于 org.json 对象的标准读取器/写入器。您必须在网上搜索实现或自己编写一个,然后注册它。你可以阅读更多关于如何实现它here

    或者,您可以接受一个字符串并返回一个字符串。只需用字符串参数构造JSONObject,返回时调用JSONObject.toString()即可。

    @POST
    @Consumes("application/json")
    @Produces("application/json")
    public String post(String jsonRequest) {
        JSONObject jsonObject = new JSONObject(jsonRequest);
        return jsonObject.toString();
    }
    

    我的建议是使用像 Jackson 这样的数据绑定框架,它可以处理模型对象(简单 POJO)的序列化和反序列化。例如,你可以有一个像

    这样的类
    public class Model {
        private String input;
        public String getInput() { return input; }
        public void setInput(String input) { this.input = input; }
    } 
    

    您可以将Model 作为方法参数

    public ReturnType sayJsonTextHello(Model model)
    

    ReturnType 也是如此。只需为您想要返回的类型创建一个 POJO。 JSON 属性基于 JavaBean 属性名称(getter/setter 遵循上面显示的命名约定)。

    要获得此支持,您可以添加此 Maven 依赖项:

    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
        <version>2.17</version>  <!-- make sure the jersey version 
                                      matches the one you are using -->
    </dependency>
    

    或者如果你不使用Maven,你可以看到this post,对于你可以独立下载的jar。

    一些资源:

    【讨论】:

    • 这解决了我的问题,但现在我得到了一些其他错误 =>无法识别的字段(类 org.json.jsonobject)未标记为可忽略。我在网上搜索并将 JsonIgnore 添加到方法并将 @JsonIgnoreProperties(ignoreUnknown = true) 添加到故事类,但我仍然遇到同样的错误。感谢您的帮助。
    • 我没有说将 JSONObject 与 Jackson 一起使用。如果您使用的是 Jackson,请使用简单的 POJOS,例如我的 Model 类。 JSONObject的内部不是JavaBean风格的,这是必需的
    • 查看Jackson Tutorial 以了解您的 POJO 的外观示例。
    【解决方案2】:

    这是因为以下问题:

    JAX-RS 不支持默认的 Jackson 映射转换。因此,如果您有以下 ajax 请求(发布):

     jQuery.ajax({
               url: "http://localhost:8081/EmailAutomated/rest/service/save",
                type: "POST",
                dataType: "JSON",
                contentType: "application/JSON",
                data: JSON.stringify(data),
                cache: false,
                context: this,
                success: function(resp){  
                     // we have the response  
                     alert("Server said123:\n '" + resp.name + "'");  
                   },  
                   error: function(e){  
                     alert('Error121212: ' + e);  
                   }  
            });
    

    在 JAX-RS 控制器端,您需要执行以下操作:

    @Path("/save")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.TEXT_PLAIN)
    public String saveDetailsUser(String userStr) {
    
        Gson gson = new Gson();
        UserDetailDTO userDetailDTO = gson.fromJson(userStr, UserDetailDTO.class);
    
        String vemail = userDetailDTO.getEMAIL();
    
        return "userDetailDTO";
    }
    

    这里请确认参数。服务接受 json 作为字符串而不是 POJO。

    肯定会奏效的。谢谢!

    【讨论】:

    • “JAX-RS 不支持默认的 Jackson 映射转换。”你能澄清一下吗?
    • 这可能是旧版本的 JAX-RS 的问题。我正在使用 jersey 1.8.3 并且规范说它不会自动将 json(来自 Ajax 帖子)转换为 POJO。
    • That's not accurate:在 Jersey 1.x 中,您可以启用 JSONConfiguration.FEATURE_POJO_MAPPING,Jackson 将用于将 JSON 转换为 Java 对象并返回。
    • 感谢您的信息。但是如果我们不启用,那么它不会进行任何转换。所以我在这里回答是因为可能其他人会面临类似的问题。谢谢卡西欧!
    • “我在这里回答是因为可能其他人会面临类似的问题。” OP 使用的是 Jersey 2.x 而不是 Jersey 1.x。请参阅web.xml 中的org.glassfish.jersey
    【解决方案3】:

    我在使用带有 HTTP/2 的 Jersey 时看到了同样的问题,如果客户端发送 HTTP/1.1 请求,例如使用 Jersey 客户端,然后它工作正常。

    如果我切换到 Jetty HTTP2 客户端发送相同的内容,我会得到 415。

    我使用的临时解决方案是 Paul Samsotha 描述的替代方案,即“接受一个字符串并返回一个字符串”,然后手动将字符串反序列化为 POJO。

    【讨论】:

      猜你喜欢
      • 2015-04-23
      • 2016-06-06
      • 2014-05-10
      • 2019-05-01
      • 1970-01-01
      相关资源
      最近更新 更多