如何使用 Apache HttpClient 4.3 处理 Cookie
2022-09-01 21:23:36
我需要在Java中实现一系列HTTP请求,并决定在4.3版(最新版本)中使用Apaches HttpClient。
问题是所有这些请求都使用cookie进行会话管理,我似乎无法找到访问该cookie并将其从请求传递到请求的方法。我在使用 curl 时的命令如下所示:
# Login
curl -c cookies -d "UserName=username&Password=password" "https://example.com/Login"
# Upload a file
curl -b cookies -F fileUpload=@IMG_0013.JPG "https://example.com/File"
# Get results of server processing file
curl -b cookies "https://example.com/File/1234/Content"
它们完美地工作。然而,使用HttpClient似乎不起作用。我尝试的是:
URI serverAddress = new URI("https://example.com/");
URI loginUri = UriBuilder.fromUri(serverAddress).segment("Login").queryParam("UserName", "username")
.queryParam("Password", "password").build();
RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH).build();
CookieStore cookieStore = new BasicCookieStore();
HttpClientContext context = HttpClientContext.create();
context.setCookieStore(cookieStore);
CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig).setDefaultCookieStore(cookieStore).build();
HttpGet httpGet = new HttpGet(loginUri);
CloseableHttpResponse loginResponse = httpClient.execute(httpGet,context);
System.out.println(context.getCookieStore().getCookies());
最后一行的输出始终为空列表。我认为它应该包含我的饼干,我说的对吗?
有人可以给我一个如何使用Apache HttpClient 4.3处理cookie的小例子吗?
谢谢