【问题标题】:jquery ajax rest call - Unsupported Media Typejquery ajax rest 调用 - 不支持的媒体类型
【发布时间】:2012-04-19 04:15:16
【问题描述】:

我正在对休息服务进行简单的 jquery ajax 调用。我将 contentType 设置为“application/json”,其余资源配置为接受“MediaType.APPLICATION_JSON”。这是一个 POST 方法。 使用此设置,我收到“Unsupported Media Type”错误。

标题信息显示 请求头中的“Content-Type application/json;charset=UTF-8”

响应显示:状态报告:不支持的媒体类型 服务器拒绝了此请求,因为请求实体的格式不受所请求方法的请求资源支持(不支持的媒体类型)。

请提供一些解决此问题的建议。

这里是sn-p的代码:

休息资源

@POST
@Produces({MediaType.APPLICATION_JSON,MediaType.TEXT_HTML})
@Consumes({MediaType.APPLICATION_JSON,MediaType.TEXT_HTML})
public Response addPerson(MyJSONObj myObj) {
    //...  
    // ...
    //...
}

jquery

$(document).ready(function() { /* put your stuff here */
    $("#Button_save").click(function(){
    var firstName = $('firstName').val(); 
    var lastName = $('lastName').val(); 
    var person = {firstName: firstName, lastName: lastName}; 
    $.ajax({

        url:'http://localhost:8080/sampleApplication/resources/personRestService/',
        type: 'POST',
        data: person,
        Accept : "application/json",
        contentType: "application/json",

        success:function(res){
        alert("it works!");
        },
        error:function(res){
            alert("Bad thing happend! " + res.statusText);
        }
    });
    });
}); 

FF Firebug 中显示的标题

响应标头

Content-Length  1117
Content-Type    text/html;charset=utf-8
Date    Thu, 05 Apr 2012 09:44:45 GMT
Server  Apache-Coyote/1.1

请求标头

Accept  */*
Accept-Encoding gzip, deflate
Accept-Language en-us,en;q=0.5
Connection  keep-alive
Content-Length  97
Content-Type    application/json; charset=UTF-8
Host    localhost:8080
Referer http://localhost:8080/sampleApplication/
User-Agent  Mozilla/5.0 (Windows NT 5.1; rv:11.0) Gecko/20100101 Firefox/11.0
X-Requested-With    XMLHttpRequest

【问题讨论】:

    标签: jquery http-headers xmlhttprequest


    【解决方案1】:

    我遇到了同样的问题,我能够通过这种方式解决它(请参阅http://www.weverwijk.net/wordpress/tag/jquery/):

    $.ajax({
        url:'http://localhost:8080/sampleApplication/resources/personRestService/',
        type:'POST',
        data: JSON.stringify(person),
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        success:function(res){
            alert("it works!");
        },
        error:function(res){
            alert("Bad thing happend! " + res.statusText);
        }
    });
    

    在 Java 方面,我添加了这些(参见 Access-Control-Allow-Origin ):

    @OPTIONS
    public Response testt(@Context HttpServletResponse serverResponse) {
        serverResponse.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
        serverResponse.addHeader("Access-Control-Allow-Credentials", "true");
        serverResponse.addHeader("Access-Control-Allow-Origin", "*");
        serverResponse.addHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With");
        serverResponse.addHeader("Access-Control-Max-Age", "60");
        return Response.ok().build();
    }
    
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(APPLICATION_JSON)
    public Response addPerson(MyJSONObj myObj, @Context HttpServletResponse serverResponse)
        serverResponse.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
        serverResponse.addHeader("Access-Control-Allow-Credentials", "true");
        serverResponse.addHeader("Access-Control-Allow-Origin", "*");
        serverResponse.addHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With");
        serverResponse.addHeader("Access-Control-Max-Age", "60");
    
        // ...
        // ...
    } 
    

    结论

    【讨论】:

    • 测试了@Options,它似乎不起作用,而且标题必须在响应中设置
    • 您能提供更多信息吗?因为我在所有项目中都使用了这段代码。
    【解决方案2】:

    我认为如果代码做了另外两件事,原来的帖子会起作用:

    data 设置为 JSON.serialize(person) 并将 dataType 设置为 'json',因为contentType 是正确的,这应该与期望消耗 json 的 @PUT 一起使用...

    【讨论】:

      【解决方案3】:

      看起来您可能正在遭受抽象泄漏的困扰。看到这个回复: JQuery's getJSON() not setting Accept header correctly?

      如果您正在进行跨域调用,那么由于 jQuery 如何从您那里抽象调用,您似乎无法设置接受标头。

      不过,您确实说服务器看到了正确的接受标头。这可能表明存在不同的问题。

      【讨论】:

        【解决方案4】:

        先试试这个 按照@wnm3 的建议将您的数据转换为 JSON 格式。

        如果仍然面临问题继续 -

        如果您的请求语法正确,这对我有帮助。这就是我所做的事情,它消除了 415 Unsupported 错误 -

        @PUT
        //REMOVE THIS LINE !!!!!! ----- @Produces(MediaType.APPLICATION_JSON)
        @Consumes(MediaType.APPLICATION_JSON)
        public Response addPerson(MyJSONObj myObj)
        
          //
          //Your code here
          return Response.ok()
                    .header("Access-Control-Allow-Origin", "*")
                    .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS, HEAD")
                    .header("Access-Control-Allow-Headers", "Content-Type,Accept,X-Requested-With,authorization")
                    .header("Access-Control-Allow-Credentials", true)
                    .build();
        } 
        

        我完全不知道,如何发出将发送和接受应用程序/json 的 CORS 请求。 @Tobias Sarnow 给出的答案部分不正确。因为您不需要接受 OPTIONS 请求的方法。即使浏览器显示它发送了 OPTIONS 请求,它仍然会寻找带有 @POST 注释的方法。因此,我没有设置过滤器或做其他事情(更精致的方式),而是通过使用另一种没有@Consumes 和@Produces 的方法来快速修复。例子-

        @PUT
        public Response addPerson() {
            return Response.ok()
                    .header("Access-Control-Allow-Origin", "*")
                    .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS, HEAD")
                    .header("Access-Control-Allow-Headers", "Content-Type,Accept,X-Requested-With,authorization")
                    .header("Access-Control-Allow-Credentials", true)
                    .build();
        }
        
        @PUT
        @Consumes(MediaType.APPLICATION_JSON)
        public Response addPerson(MyJSONObj myObj)
          //
          //Your code here
          //
          return Response.ok()
                    .header("Access-Control-Allow-Origin", "*")
                    .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS, HEAD")
                    .header("Access-Control-Allow-Headers", "Content-Type,Accept,X-Requested-With,authorization")
                    .header("Access-Control-Allow-Credentials", true)
                    .build();
        } 
        

        所以这里发生的情况是,OPTIONS 的初始 CORS 由第一种方法处理,然后第二种方法处理原始 PUT 请求。

        我将这个答案放在这里,因为我花了 3-4 天的时间才弄清楚为什么我的 PUT 请求没有通过。所以它可能对遇到 415 错误的人有所帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-10-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-21
          相关资源
          最近更新 更多