有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java HttpClient无法访问GET方法中的Cookie

我正在编写两个函数——第一个是登录某个站点,第二个是使用基于cookies的“登录”上下文获取主页。尽管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) 个答案

  1. # 1 楼答案

    解决方案非常简单——httpclient没有为cookies使用任何默认的内存存储,我错误地认为它有一些

    当我将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]);
    }