【问题标题】:How to set and check cookies wih JAX-RS in a java library code如何在 Java 库代码中使用 JAX-RS 设置和检查 cookie
【发布时间】:2018-02-09 03:14:43
【问题描述】:

我是 RESTful API 的菜鸟,我正在尝试构建一个 java 库,该库使用 REST 调用获取身份验证令牌,然后我打算将其存储在 cookie 中,以便我可以将其用于进一步的 API 调用。我已经使用以下代码完成了它:

如何做到这一点?

NewCookie cookie4 = new NewCookie("name", "123");
Response.ok("OK").cookie(cookie4).build();
//call made to retrieve the cookie here, is defined below

我有一个像这样的获取 cookie 方法

  @GET
    public Response getCookie(@CookieParam("name") Cookie cookie) {
            if (cookie == null) {
                System.out.println("IN NULL");
                return Response.serverError().entity("ERROR").build();
            } else {
                return Response.ok(cookie.getValue()).build();
            }
    }

现在我尝试在上面设置 cookie 后检索它:

  Cookie cookieval = null;
    Response check = getCookie(cookieval);
    System.out.println(cookieval.getName());
    System.out.println(cookieval.getValue());

它不起作用,流程进入上述getcookie方法中的cookie null部分。我正在使用 JUNIT 测试用例对其进行测试。 cookie 仅与请求对象一起持久化,否则

如果信息不充分或需要更多信息,请告诉我

【问题讨论】:

  • 如果是测试用例,请发布完整可运行代码示例。

标签: java rest jax-rs setcookie


【解决方案1】:

我看到了您的代码,看起来问题是您将 cookieval 声明为“null”的第一行,然后将 null 值传递给将其识别为 null 的方法 getCookie。

Cookie cookieval = null;
Response check = getCookie(cookieval);
System.out.println(cookieval.getName());
System.out.println(cookieval.getValue());

【讨论】:

    猜你喜欢
    • 2015-03-16
    • 1970-01-01
    • 2011-03-26
    • 2020-10-14
    • 2017-01-04
    • 2014-10-03
    • 2013-08-27
    • 2015-06-16
    • 2021-12-18
    相关资源
    最近更新 更多