繁体   English   中英

Jersey 415不支持的媒体类型

[英]Jersey 415 Unsupported Media Type

自数小时以来,我一直在尝试更正http错误415 Unsupported Media Type但它仍显示不支持的媒体页面。 我在邮递员中添加标题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>

通过MessageBodyWriterMessageBodyReader ,如何在响应流和请求流之间MessageBodyWriter序列化和反序列化我们的对象。

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

Jersey没有针对org.json对象的任何标准读取器/写入器。 您将不得不在网上搜索实现或自己编写一个实现,然后进行注册。 您可以在此处阅读有关如何实现它的更多信息。

或者,您可以接受一个String并返回一个String。 只需使用string参数构造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,则可以查看此帖子 ,您可以独立下载jar。

一些资源:

其原因如下:

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作为String而不是POJO。

当然可以。 谢谢!

在将Jersey / 2与HTTP / 2一起使用时,我也看到过同样的问题,如果客户端发送HTTP / 1.1请求(例如使用Jersey客户端),则可以正常工作。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM