Popular Posts
javax.net.ssl.SSLHandshakeException: Connection closed by peer in Android 5.0 Lollipop Recently, there is a error occurs when access website via ssl connection like below although it worked fine several days ago. // Enable SSL... Hierarchical Query Start with connect by prior 階層式查詢用法 SELECT s.role_id, s.role_name, s.role_base_on, b.role_name role_base_on_name FROM m_usr_role s... Tired of Hibernate? Try JDBI in your code JDBI Quick sample ICategoryDAO.java : create a data access interface (implement is not required) package com.prhythm.erotic.task.data....
Blog Archive
Stats
set/remove cookie using HttpClient
HttpClient version : 3.1
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;

public class CookieManager {

    public static String getCookieValue(HttpClient client, String key) {
        Cookie cookie = getCookie(client, key);
        return cookie == null ? null : cookie.getValue();
    }

    public static Cookie getCookie(HttpClient client, String key) {
        Cookie[] cookies = client.getState().getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(key))
                return cookie;
        }
        return null;
    }

    public static void setCookie(HttpClient client, String key, String value) {
        Cookie cookie = new Cookie("", key, value);
        setCookie(client, cookie);
    }

    // 設定cookie的值
    public static void setCookie(HttpClient client, Cookie cookie) {
        Cookie[] cookies = client.getState().getCookies();

        if (cookies.length > 0)
            cookie.setDomain(cookies[0].getDomain());
        boolean isContained = false; // 檢查是否有值
        for (Cookie ck : cookies) {
            if (cookie.getName().equals(ck.getName()))
                isContained = true;
        }
        if (!isContained) { // 如果未設定, 直接加入
            client.getState().addCookie(cookie);
            return;
        }

        client.getState().clearCookies();
        for (Cookie ck : cookies) {
            if (cookie.getName().equals(ck.getName()))
                ck.setValue(cookie.getValue()); // 取代原有值
            client.getState().addCookie(ck);
        }
    }
}