Search This Blog

2013-05-19

Java解析带httponly的cookie

以前接手过一个爬虫项目,使用了java.net包,时间紧迫,我就没有换成HttpClient。后来需要登陆一个网站,所以需要用cookie,但是提交账户以后无法登陆,发现是一些重要cookie没有提交,原因是很多重要的cookie都带了httponly,解析不出来(这些cookie直接被忽略,异常也被吃掉不打印)。

解决思路是先把cookie里面的httponly去掉,然后再提交给系统解析,这可以通过覆盖java.net.CookieManager的put方法实现。
下面的这段源码不是我现在重写的,之前在测试工程写过一个demo,现在只是略作修改。
Pre[-]
import java.io.IOException;
import java.net.CookieManager;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

public class HttponlyFilteredCookieManager extends CookieManager {
    private static final Pattern HTTPONLY_PATTERN = Pattern.compile(";\\s*httponly",
            Pattern.CASE_INSENSITIVE);

    /**
     * filter all httponly in the cookie, else java.net.HttpCookie can't parse it
     */
    @Override
    public void put(URI uri, Map<String, List<String>> responseHeaders) throws IOException {
        Map<String, List<String>> newResponseHeaders = new HashMap<>(responseHeaders.size());
        for (String key : responseHeaders.keySet()) {
            List<String> valueList = responseHeaders.get(key);
            List<String> newValueList = new ArrayList<String>(valueList.size());
            for (String value : valueList) {
                newValueList.add(HTTPONLY_PATTERN.matcher(value).replaceAll(""));
            }
            newResponseHeaders.put(key, newValueList);
        }
        super.put(uri, newResponseHeaders);
    }
}

=文章版本=

20130518

No comments:

Post a Comment