【发布时间】:2019-08-16 15:54:13
【问题描述】:
我必须使用带有 Spring Boot 的 Java 通过 REST 接口将文档上传到归档系统。
有人告诉我首先使用基本身份验证发出 GET 请求。这将为我提供响应中的授权 cookie。然后我必须将这些 cookie 与 POST 请求一起发送以进行实际归档。
GET 工作正常。 我在互联网上读到我应该在“Set-Cookie”-响应的标头中获取 cookie。 但我没有得到 cookie。
奇怪的是,如果我使用 Postman 执行请求,我会得到 2 个 cookie(“AuthSessionId”和“ClientId”)。 为什么我不以编程方式获取这些?
作为旁注:邮递员还显示我在响应中有 15 个(其他?)标题。我在我的 ClientHttpResponse 中找到这些没有问题
这里有一些代码:
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
}
【问题讨论】:
-
如何构建请求工厂?例如,如果您使用 Apache 的 HttpClient 实现,它会拦截 cookie 标头并将其删除,将它们保存在 cookie 存储中,而 Spring 的 http 接口不会公开。在这种情况下,您最好自己使用 Apache HttpClient 类并阅读如何访问 cookie。