Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
122 views
in Technique[技术] by (71.8m points)

java - URLConnection with Cookies?

I'm trying to make a URLConnection that supports cookies. According to the documentation I can use:

CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);

I couldn't get this code to work, then I saw this only works for API 9 (2.3). However, I don't get an error using CookieManager in an older emulator, CookieManager exists, but can't be constructed. Is there any way to make this work for earlier versions? I tried:

            cookieManager.setAcceptCookie(true);
            URLConnection con = u.openConnection();

            con.setRequestProperty("Cookie", cookieManager.getInstance().getCookie(url););
            con.setDoOutput(true);
            con.connect();
            String addCookie = con.getHeaderField("Set-Cookie");
            System.out.println(con.getHeaderFields().toString());
            if (addCookie!=null) {
                cookieManager.getInstance().setCookie(url, addCookie);
            }

but this doesn't work.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I was able to enable cookies using Ian Brown's CookieManager class: http://www.hccp.org/java-net-cookie-how-to.html

I renamed it to IansCookieManager, set a class variable _CM = new IansCookieManager, now it's simple:

            URLConnection conn = u.openConnection();
            _CM.setCookies(conn);
            conn.connect();
            _CM.storeCookies(conn);
            ... 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...