【发布时间】:2017-07-05 22:02:16
【问题描述】:
我无法弄清楚如何使用 Apache HttpComponents/HttpClient Fluent API 并让它正确地将 cookie 发送回需要登录的 Web 服务器,然后发送回 cookie 以访问网站的其他部分。我使用的是 4.5.3 版本。
根据 Fluent API 教程,您可以使用(HttpComponents)执行器“以便在特定的安全上下文中执行请求,从而缓存身份验证详细信息并重新用于后续请求。” https://hc.apache.org/httpcomponents-client-4.5.x/tutorial/html/fluent.html
所以我尝试了,但在登录后尝试访问另一个页面时,我得到了 403 Access Denied。 这是我尝试过的代码:
CookieStore httpCookieStore = new BasicCookieStore();
List<Cookie> cookies = httpCookieStore.getCookies();
String username = "admin";
String password = "admin";
Executor httpExecutor = Executor.newInstance().auth(username, password);
httpExecutor.use(httpCookieStore);
Response response = httpExecutor.execute(Request.Get("http://myserver.example.com/login").useExpectContinue());
String loginOutput = response.returnContent().asString();
System.out.println(loginOutput); // works - gets the expected page
String swaggerUrl = "http://myserver.example.com/swagger/index.html";
response = httpExecutor.execute(Request.Get(swaggerUrl));
HttpResponse httpResponse = response.returnResponse();
System.out.println(httpResponse); // Response is 403 Access Denied
// prints: HttpResponseProxy{HTTP/1.1 403 Access Denied [X-Content-Type-Options: nosniff, X-XSS-Protection: 1; mode=block, Pragma: no-cache, X-Frame-Options: DENY, Content-Type: text/html;charset=ISO-8859-1, Cache-Control: must-revalidate,no-cache,no-store, Content-Length: 1391, Server: Jetty(8.1.16.v20140903)] [Content-Type: text/html; charset=ISO-8859-1,Content-Length: 1391,Chunked: false]}
我在登录后检查了CookieStore 的内容,它有正确的cookie:
System.out.println(httpCookieStore.getCookies().size()); // prints 1
System.out.println(httpCookieStore.getCookies().get(0));
// prints: [version: 0][name: JSESSIONID][value: 14b1yp7hf85es1vc6zpe2y376n][domain: myserver.example.com][path: /][expiry: null]
所以我也尝试将 cookie 显式添加到 GET 请求的 Header 中,但仍然失败并出现相同的 403 Access Denied 错误:
CookieStore httpCookieStore = new BasicCookieStore();
List<Cookie> cookies = httpCookieStore.getCookies();
String username = "admin";
String password = "admin";
Executor httpExecutor = Executor.newInstance().auth(username, password);
httpExecutor.use(httpCookieStore);
Response response = httpExecutor.execute(Request.Get("http://myserver.example.com/login").useExpectContinue());
String loginOutput = response.returnContent().asString();
System.out.println(loginOutput); // works - gets the expected page
String swaggerUrl = "http://myserver.example.com/swagger/index.html";
response = httpExecutor.execute(Request.Get(swaggerUrl).addHeader(authCookieName, authCookieValue));
HttpResponse httpResponse = response.returnResponse();
System.out.println(httpResponse); // Response is 403 Access Denied
有任何想法如何使用 fluent API 进行这项工作吗?
【问题讨论】: