2014-04-04 2 views
0

두 가지 기능을 쓰고 있습니다. 첫 번째는 일부 사이트에 로그인하고 두 번째 기능은 쿠키를 기반으로 "로그인 된"컨텍스트를 사용하여 기본 페이지를 가져옵니다. 사실 쿠키가 두 번째 방법 (내가 HttpClientContext.getCookieStore().getCookies()을 사용하여 압축을 풀었고 확인 된 것 같습니다)에도 사용 가능하지만 메인 페이지는 로그인하지 않은 사용자를 위해 버전을 표시하는 것으로 보입니다. 사이트에 로그인 할 때 사용HttpClient - GET 메서드로 쿠키에 액세스 할 수 없습니다.

코드 :

// 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 요청이 쿠키 저장소를 사용

:

// 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는 인수로 전달됩니다) 메인 페이지의 콘텐츠를 얻기 위해 사용하고 계십니까? 페이지의 "로그인 한"버전을 가져올 수없는 이유는 무엇입니까?

답변

0

솔루션은 매우 간단했습니다. - httpclient는 쿠키 용 기본 메모리 내장 저장소를 사용하지 않았으며, 일부 쿠키가 있다는 잘못된 가정을하고있었습니다.

쿠키를 측면에 저장하고 직렬화 한 다음 비 직렬화 된 쿠키로 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]); 
} 
관련 문제