使用 JAX-RS Jersey 服务使用 Cookie 和 JSON

Consume Cookie and JSON with JAX-RS Jersey Service

我正在使用 jQuery 代码和方法 POST 将这些数据发送到 Restful Web 服务(泽西岛):

var dataString = {"id":1,"status":"passed","session":"nothing"};
$.post("https://localhost:8443/pv01/ws/user/cookie", dataString);

使用这些数据,我发送了一个 cookie。 cookie 中的数据来自外部 API.

我面临的问题是如何同时接收 cookie 值和 dataString。

这是我的 Java 读取 Cookie 的代码:

@POST
@Path("cookie")    
public String cookie(@CookieParam("L14c") String str) {        
    Logger.getLogger(Main.class.getName()).log(Level.INFO, "message : " + str );
    return str;
}

对于数据,我可以这样做:

@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("cookie")
public String cookie(DataString dataString) {        
    Logger.getLogger(Main.class.getName()).log(Level.INFO, "message : " + dataString );
    return "ok";
}

但是当我结合这两种方法来接受 cookie 和 JSON dataString 时,我得到错误 415,不支持的媒体类型!

我试图查看 HTTP Headers,但我只能访问 cookie。

问题出在 jQuery 请求上。看起来 Content-Type 默认为 application/x-www-form-urlencoded。您应该使用像 Firebug 这样的浏览器调试器。更容易发现这些东西。

根据我的测试,它应该适用于类似

的东西
$.ajax({
    url: theUrl,
    type: "POST",
    data: JSON.stringify(dataString),
    dataType: "json",
    contentType: "application/json",
    success: function(response) {
        alert(JSON.stringify(response));
    }
});