我在让 Jersey 和 Jquery 以 JSON 格式通信数据时遇到了一些麻烦。在以下最小示例中,始终向调用 JQuery 客户端返回 HTTP 204。
@Path("/path")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class Resource {
@POST
public ReturnData postSomething(@Valid Data data) {
Log("success");
...
ReturnData returnData = ...;
return returnData;
}
}
我使用以下 JQuery 代码,并在每次发布后调用错误函数。
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: url,
data: '{"data": "data"}',
dataType: "json",
error: function(data){
alert("fail");
},
success: function(data){
alert("success");
}
});
在 Firebug 中,我看到带有上述设置的以下 HTTP 请求/响应:
OPTIONS /path HTTP/1.1
Host: 192.168.15.109:8080
User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:12.0) Gecko/20100101 Firefox/12.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Origin: http://localhost
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Pragma: no-cache
Cache-Control: no-cache
HTTP/1.1 204 No Content
Date: Thu, 24 May 2012 16:10:57 GMT
Allow: OPTIONS,POST
起初,我在 JQuery 帖子中尝试了没有 contentType: "application/json; charset=utf-8" 的设置,结果如下:
POST /path HTTP/1.1
Host: 192.168.15.109:8080
User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:12.0) Gecko/20100101 Firefox/12.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://localhost/test.html
Content-Length: 104
Origin: http://localhost
Pragma: no-cache
Cache-Control: no-cache
HTTP/1.1 415 Unsupported Media Type
Date: Thu, 24 May 2012 16:08:55 GMT
Content-Type: text/plain;charset=UTF-8
Cache-Control: must-revalidate,no-cache,no-store
Content-Length: 72
Cache-Control: no-cache
我认为客户端和服务器由于某种原因找不到他们都同意的数据类型。我觉得奇怪的是,在将 contentType 设置为 JSON 时,接受标头不包含 JSON。
日志(“成功”);在服务器端永远不会执行。
谁能指出我正确的方向?