簡體   English   中英

HttpClient 4.2.5與Cookie配合使用

[英]HttpClient 4.2.5 workings with cookies

我剛剛開始使用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;
}

也許嘗試這樣設置自己的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);

你可以在自己的Google Checkout的完整代碼javautils回購這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM