jquery ajax 休息调用 - 不支持的媒体类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10028335/
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-26 08:44:22  来源:igfitidea点击:

jquery ajax rest call - Unsupported Media Type

jqueryhttp-headersxmlhttprequest

提问by RJ.

I'm having a simple jquery ajax call to a rest service. I am setting the contentType as "application/json" and the rest resource is configured to accept "MediaType.APPLICATION_JSON". This is a POST method. With this setup, I am getting "Unsupported Media Type" error.

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

The header info shows"Content-Type application/json; charset=UTF-8" in the request header

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

Response shows: Status report: Unsupported Media Type The server refused this request because the request entity is in a format not supported by the requested resource for the requested method (Unsupported Media Type).

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

Please provide some pointers to resolve this issue.

请提供一些指示以解决此问题。

Here is the code snippet:

这是代码片段:

Rest Resource

休息资源

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

Headers as displayed in FF Firebug

FF Firebug 中显示的标题

Response Headers

响应头

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

Request Headers

请求头

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

回答by Tobias Sarnow

i had the same problem and I was able to solve it that way (see http://www.weverwijk.net/wordpress/tag/jquery/):

我遇到了同样的问题,我能够以这种方式解决它(请参阅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);
    }
});

On Java side I added these (see Access-Control-Allow-Origin ):

在 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");

    // ...
    // ...
} 

Conclusion

结论

  • JSON 对象自动传输和转换(更多详细信息请参阅为 RESTful Web 服务配置 JSON
  • POST提交
  • 跨域(同源策略)
  • Firefox 工作(见@Option 标签)

回答by wnm3

I think the original post would have worked had the code done two additional things:

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

set the datato JSON.serialize(person)and set the dataTypeto 'json'since the contentType was correct, this should work with the @PUT expecting to consume json...

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

回答by Saurabh Gupta

TRY THIS FIRSTConvert your data to JSON format as @wnm3 suggested.

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

IF STILL FACING PROBLEM CONTINUE -

如果仍然面临问题继续 -

This helped me, if your Request syntax is correct. This is the thing I did which remove the 415 Unsupported error -

如果您的请求语法正确,这对我有帮助。这是我做的事情,它删除了 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();
} 

I exactly don't know, how to make CORS request which will send and accept application/json. The answer given by @Tobias Sarnow is partially incorrect. As you don't need method which accepts OPTIONS request. Even if the browser is showing that it sends OPTIONS request, it will still look for method with @POST annotation. So instead of putting up a filter or doing something else(more refined ways) I did through quick fix by using another method with no @Consumes and @Produces. Example-

我完全不知道,如何发出将发送和接受应用程序/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();
} 

So what's happening here is as initial CORS for OPTIONS is handled by first method then the second method handles the original PUT request.

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

I am putting this answer here as it took me 3-4 days to figure out why my PUT request was not going through. So it may help someone who is having 415 error.

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

回答by GrooveStomp

It looks like you may be suffering from a leaky abstraction. See this response: JQuery's getJSON() not setting Accept header correctly?

看起来您可能正在遭受泄漏的抽象。请参阅此回复: JQuery 的 getJSON() 未正确设置 Accept 标头?

If you're doing a cross-domain call, then it seems you are not able to set the accept header due to how jQuery abstracts the call from you.

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

You do say that the server is seeing the correct accept header, though. That could be indicating a different issue.

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