gpt4 book ai didi

java - 当从 java VM 调用设置 cookie 的 REST 服务时,cookie 是如何工作的?

转载 作者:行者123 更新时间:2023-12-01 11:45:45 25 4
gpt4 key购买 nike

我正在学习如何使用 HP Quality Center 的 REST API 来查询和操作数据。与 REST 标准不同,该 API 并非完全无状态。它使用 cookie 来存储身份验证 session 。

我尝试使用 Jersey 客户端库来实现一个非常简单的测试。我可以通过发送我的凭据来成功验证我的用户身份。 API 引用声称这将设置一个 cookie,我很乐意进一步调用 REST API。然而,一个简单的“is-authenticated”调用会返回 401,身份验证失败。

我有一种感觉,cookie 的写入或读取工作不正常,因为其他一切似乎都正常工作。但我无法查明在不涉及浏览器的情况下是否或如何设置和读取 cookie。那么,当从 java VM 调用设置 cookie 的 REST 服务时,cookie 是如何工作的呢?它到底有用吗?它们存储在哪里?

我使用 Eclipse Kepler 作为我的 IDE(如果这很重要的话),以及 32 位 java 1.6 JDK 和 JRE。

代码和响应字符串如下:

<强>1。登录:

    Client client = ClientBuilder.newClient();
Response response = client
.target("http://[host]:[port]").path("qcbin/authentication-
point/alm-authenticate")
.request().post(Entity.entity("<alm-authentication>
<user>username</user>
<password>secret</password></alm-authentication>",
MediaType.TEXT_XML_TYPE));

System.out.println(response.toString());

输出:

InboundJaxrsResponse{ClientResponse{method=POST, 
uri=http://[host]:[port]/qcbin/authentication-point/alm-authenticate,
status=200, reason=OK}}

API返回说明:

One of:

HTTP code 200 and sets the LWSSO cookie (LWSSO_COOKIE_KEY).

HTTP code 401 for non-authenticated request. Sends header WWW-Authenticate: ALMAUTH




2.验证登录:

response = client.target("http://[host]:[port]")
.path("qcbin/rest/is-authenticated")
.request().get();

System.out.println(response.toString());

输出:

InboundJaxrsResponse{ClientResponse{method=GET,     
uri=http://[host]:[port]/rest/is-authenticated, status=401,
reason=Authentication failed. Browser based integrations - to login append
'?login-form-required=y to the url you tried to access.}}

PS:?login-form-required=y 添加到 URL,在浏览器中调用时会弹出登录窗口,但此处不会。将该行附加到 URL 实际上仍然会给出相同的错误消息,并建议再次附加它。此外,当在浏览器中调用时,即使没有登录表单,is-authenticated也会返回 200,表示成功。

最佳答案

当您登录时,您将获得一个 cookie,它是一个名称加一个值。

REST 服务器希望您在发出的每个请求的请求 header 中传递此信息。

查看通过 client.request() 获得的对象;应该有一种方法来指定发送到服务器的附加 header 。 header 名称必须为 Cookie, header 值必须为 name=value

因此,如果服务器响应名为 sessionID 且值为 1234 的 cookie,那么您需要类似以下内容:

client.request().header("Cookie", "sessionID=1234")

相关:

关于java - 当从 java VM 调用设置 cookie 的 REST 服务时,cookie 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29148482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com