简体   繁体   中英

HttpClient 4.2.5 workings with cookies

i just started to work with the HttpClient and i use it to login on my website. The problem is that i can't get cookies and so i can't stay logged in.

Here is my code, probably not very good... Can someone tell me how to handle cookies with this library? Or maybe it exists a documentation or tutorial where i can learn more about? (i already checked online documentation, wasn't very helpuf).

public MyHttpClient() {     
    this.client = new DefaultHttpClient();
    this.client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
}       

/**
 * Retourne le contenu d'une requête POST
 * @param url L'url de la requêtes
 * @return Le contenu de la réponse à a reque^te
 */
public String sendRequest(String[] args){     
    String requestResponse = "";
    HttpPost post = new HttpPost(MyHttpClient.AJAX_API_URL);
    try {            
        //Test avec httpClient
        HttpResponse response;
        HttpEntity entity;

        //Déclaration de la liste des valeurs
        List<BasicNameValuePair> listKeys = new ArrayList<>();
        for(int i = 0; i < args.length; i += 2){
            listKeys.add(new BasicNameValuePair(args[i],args[i+1]));
        }

        //On ajoute les clefs à la requete
        post.setEntity(new UrlEncodedFormEntity(listKeys,Consts.UTF_8));

        response = client.execute(post);            
        entity = response.getEntity();

        //Récupération des cookies
        for(Cookie cookie : client.getCookieStore().getCookies()){
            this.listCookies.add(cookie);                
            Logger.getLogger(MyHttpClient.class.getName()).log(Level.INFO, "Cookie "+cookie.getName());
        }

        requestResponse = EntityUtils.toString(entity);
    } catch (IOException ex) {
        Logger.getLogger(MyHttpClient.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        post.releaseConnection();
    }

    return requestResponse;
}

Maybe try setting your own cookieStore like this:

private HttpClient client;
private CookieStore cookieStore;
private HttpContext httpContext;

And then in initialization:

            cookieStore = new BasicCookieStore();
            httpContext = new BasicHttpContext();
            httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

In your sendRequest method:

HttpResponse response = client.execute(post, httpContext);

You can checkout the full code in my javautils repo here

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