HttpClient 4.2.5与cookie一起使用

时间:2013-05-31 04:33:58

标签: java apache-httpclient-4.x

我刚刚开始使用HttpClient,我用它来登录我的网站。问题是我无法获得cookie,所以我无法保持登录状态。

这是我的代码,可能不是很好...... 有人能告诉我如何处理这个库的cookie吗?或者它可能存在一个文档或教程,我可以在其中了解更多信息? (我已经查过在线文档,不是很有帮助)。

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;
}

1 个答案:

答案 0 :(得分:0)

也许尝试像这样设置自己的cookieStore

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

然后在初始化中:

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

sendRequest方法中:

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

您可以在我的javautils回购here

中查看完整代码