我需要在Java中实现一系列HTTP请求,并决定使用Apaches HttpClient 4.3版本(最新版本)。
问题是所有这些请求都使用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());
最后一行的输出始终是一个空列表。我认为它应该包含我的Cookie,我对吗?
有人能给我一个使用Apache HttpClient 4.3处理cookie的小例子吗?
谢谢
UriBuilder
是什么?在Apache Commons中,我看到了URIBuilder
(大写的R和I)。 - Line