Pregunta

I'm trying to log in to a web app on behalf of a user with HttpClient 4.3.3 in the following way:

CloseableHttpClient client = HttpClients.createDefault();
CookieStore cookies = new BasicCookieStore();
HttpPost httpPost = new HttpPost(LOGIN_URL);

List <NameValuePair> paramList = new ArrayList <NameValuePair>();
paramList.add(new BasicNameValuePair("userid", username));
paramList.add(new BasicNameValuePair("pword", password));

httpPost.setEntity(new UrlEncodedFormEntity(paramList));
HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookies);
CloseableHttpResponse response = client.execute(httpPost, httpContext);

...and that's fine. The result I get back is the HTML for the web app menu, so I'm successfully logged in. There's lots of links in the HTML, so I use a regex and pull one of them out. Then I do this:

HttpGet httpGet = new HttpGet(URL_I_PULLED_FROM_HTML);
httpContext = new BasicHttpContext();
httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookies);
response = client.execute(httpGet);
client.close();

Now instead of getting the intended HTML from response, I just get the HTML for a "User not logged in" page. It's like the cookies aren't working. I've tried re-initializing the http client before making the subsequent GET request, but it doesn't make a difference. Is there something I'm missing here?

Also, after the first request (the login POST), the CookieStore object has cookies, as shown using:

for (Cookie cookie : cookies.getCookies()) {
    LOG.info(cookie.getName());
    LOG.info(cookie.getValue());
}

It shows 3 cookies. They're names are JSESSIONID, TS7181ec and TSd9290f (all 3 have values).

¿Fue útil?

Solución

Sorry, rookie mistake on my part. No wonder it wasn't working, the second request in my question (the GET, after logging in) wasn't actually passing in the httpContext object that contains the cookies.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top