如何使用Apache HttpClient 4.3处理Cookie

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的小例子吗?

谢谢

ok2*_*k2c 8

您的代码对我来说看起来不错(除了不释放资源,但我认为为简洁起见省略了异常处理).cookie存储空的原因可能是目标服务器违反了实际的cookie策略(在您的情况下是BEST_MATCH).因此,服务器发送的cookie被拒绝为无效.你可以发现,如果这是由所描述的上下文/线记录转弯的情况下(和其他有用的上下文信息)在这里