如何以编程方式获取授权 cookie



我必须使用带有 spring boot 的 Java 通过 REST 接口将文档上传到归档系统。

我被告知首先使用基本身份验证发出GET请求。这将在响应中为我提供授权cookie。然后,我必须将这些cookie与POST请求一起发送以进行实际存档。

GET工作正常。我在互联网上读到我应该在响应的"Set-Cookie"-标题中获取cookie。但我没有得到饼干。

奇怪的是,如果我使用 Postman 执行请求,我会得到 2 个 cookie("AuthSessionId"和"ClientId"(。为什么我不以编程方式获取这些内容?

作为旁注:邮递员还显示我在响应中得到了 15 个(其他?(标头。我在我的客户端HTTP响应中找到这些没有问题

下面是一些代码:

ClientHttpResponse response = request.execute();
    // this is  org.springframework.http.client.ClientHttpResponse
List<String> cookies =  response.getHeaders().get(HttpHeaders.SET_COOKIE);
if (cookies != null) {
    for (String cook : cookies) {
         System.out.println("cookie: " + cook);
    }
} else {
    System.out.println("no cookie in " + HttpHeaders.SET_COOKIE); // this is what I get
}

kumesana是对的。Cookie 被过滤掉并放入 CookieStore 中。如果我之前设置了这个,我可以在请求完成后获取它们:

CookieStore cookieStore = new BasicCookieStore();
CloseableHttpClient client = HttpClientBuilder
            .create()
            .setDefaultCredentialsProvider(credentialsProvider)  
            .setConnectionManager(poolingConnectionManager)    
            .setDefaultCookieStore(cookieStore)
            .build();

最新更新