ali*_*ali 23 java apache cookies curl apache-httpclient-4.x
我需要在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"
Run Code Online (Sandbox Code Playgroud)
他们工作得很好.然而,使用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());
Run Code Online (Sandbox Code Playgroud)
最后一行的输出始终为空列表.我认为它应该包含我的Cookie,对吗?
有人可以给我一个关于如何使用Apache HttpClient 4.3处理cookie的小例子吗?
谢谢