HttpClient - 无法在GET方法中访问cookie

时间:2014-04-04 15:41:53

标签: java cookies apache-httpclient-4.x

我正在编写两个函数 - 第一个用于登录某个站点,第二个用于使用基于cookie的“登录”上下文获取主页。尽管cookie在第二种方法中可用(我使用HttpClientContext.getCookieStore().getCookies()提取它们并且它们似乎没问题)主页似乎正在为非登录用户显示其版本。

用于登录网站的代码:

    // Prepare cookie store
    RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build();
    CookieStore cookieStore = new BasicCookieStore();
    HttpClientContext context = HttpClientContext.create();
    context.setCookieStore(cookieStore);

    // Prepare http Client
    CloseableHttpClient httpclient = HttpClients
            .custom()
            .setDefaultRequestConfig(globalConfig)
            .setDefaultCookieStore(cookieStore)
            .build();

    // Prepare post for login page
    HttpPost httpPost = new HttpPost("http://somesite/login");

    // Prepare nvps store
    List<NameValuePair> nvps = new ArrayList<>();
    nvps.add(new BasicNameValuePair("login", "***"));
    nvps.add(new BasicNameValuePair("passwd", "***"));

    // Set proper entity
    httpPost.setEntity(new UrlEncodedFormEntity(nvps));

    CloseableHttpResponse response = httpclient.execute(httpPost);
    try {
        HttpEntity entity = response.getEntity();
        EntityUtils.consume(entity);
    } finally {
        response.close();
    }

用于获取主页内容的代码(URIBuilder作为参数传递):

    // Build URI
    URI uri = builder.build();
    HttpGet httpget = new HttpGet(uri);

    // Prepare cookie store
    RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build();
    CookieStore cookieStore = new BasicCookieStore();
    HttpClientContext context = HttpClientContext.create();
    context.setCookieStore(cookieStore);

    // Prepare http Client
    CloseableHttpClient httpclient = HttpClients
            .custom()
            .setDefaultRequestConfig(globalConfig)
            .setDefaultCookieStore(cookieStore)
            .build();

    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    String entityContents = "";
    int respCode = response.getStatusLine().getStatusCode();

    if (entity != null) {
        entityContents = EntityUtils.toString(entity, "UTF-8");
        EntityUtils.consume(entity);
    }
    httpclient.close();

我的GET请求是否使用cookie商店?为什么我无法获得页面的“登录”版本?

1 个答案:

答案 0 :(得分:0)

解决方案非常简单 - httpclient没有使用任何默认的内存存储区来处理cookie,我假设它有一些错误的假设。

当我将cookie存储在一边(并将其序列化)然后 - 使用反序列化的cookie启动GET请求 - 一切运行良好。

所以在POST请求(登录)之后:

CookieStore cookieStore = httpClient.getCookieStore();
List<Cookie> cookies = cookieStore.getCookies();

然后 - 以某种方式序列化该列表。 在做GET请求时:

CookieStore cookieStore = new BasicCookieStore();
for(int i =0;i<cookies.length;i++) {
    cookieStore.addCookie(cookies[i]);
}