简体   繁体   中英

apache commons httpclient 4.23 form login problems different session cookies used in different requests

I have a protected resource which requires me to login. Im using the commons client with the following code block.

    HttpClient httpClient = new HttpClient();
    httpClient.getParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
    httpClient.getParams().setParameter("http.protocol.single-cookie-header", Boolean.TRUE);

    PostMethod postMethod = new PostMethod("/admin/adminlogon.do");
    postMethod.setRequestEntity(new StringRequestEntity("action=logon&adminUser=admin&adminPassword=password",
            "application/x-www-form-urlencoded",
            "UTF-8"));
    postMethod.addParameter("action","logon");
    postMethod.addParameter("adminUser","admin");
    postMethod.addParameter("adminPassword","password");

    httpClient.executeMethod(postMethod);
    String response2 = postMethod.getResponseBodyAsString();

Above is where I basically login. This works fine im getting a nice little JSESSIONID cookie back.

    GetMethod get = new GetMethod("/admin/api.do?action=getSomeJson");
    httpClient.executeMethod(get);

When I check the logic on the sever the for the 2nd request I notice that we are using a different JSESSIONID. Therefore the get seems to fail to log in. I was under the impression the httpClient managed the cookies and sent the same cookie back. When I log into my app normally through the UI I see the same cookie in each request just not in the this test code.

    String s = get.getResponseBodyAsString();
    get.releaseConnection();

Do I need to do something with the httpClient to ensure it uses the same cookies from the first post request when it does its get request??

Thanks in advance.

Your assumption regarding HTTP client cookie behavior is correct. In your case your not use the same httpClient instance. To fix it you need to allocate the httpClient only once (in PostConstructor):

       httpClient = new DefaultHttpClient(); // or new HttpClient();

Then, you perform your calls using the same instance of the client. The client will take a cookie from a response, will store it in the cookieStore and will send it with the next request.

[Added after the comment] The following code works for me:

    httpClient = new DefaultHttpClient();
    // Create a local instance of cookie store
    cookieStore = new BasicCookieStore();
    // Set the store
    httpClient.setCookieStore(cookieStore);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM