简体   繁体   English

HttpClient 4.2.5与Cookie配合使用

[英]HttpClient 4.2.5 workings with cookies

i just started to work with the HttpClient and i use it to login on my website. 我刚刚开始使用HttpClient,并使用它来登录我的网站。 The problem is that i can't get cookies and so i can't stay logged in. 问题是我无法获取Cookie,因此无法保持登录状态。

Here is my code, probably not very good... Can someone tell me how to handle cookies with this library? 这是我的代码,可能不是很好。有人可以告诉我如何使用此库处理cookie吗? 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: 也许尝试这样设置自己的cookieStore

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: 在您的sendRequest方法中:

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

You can checkout the full code in my javautils repo here 你可以在自己的Google Checkout的完整代码javautils回购这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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