本文介绍了URLConnection 与 Cookies?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个支持 cookie 的 URLConnection.根据我可以使用的文档:

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

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

我无法让这段代码工作,然后我发现这仅适用于 API 9 (2.3).但是,在较旧的模拟器中使用 CookieManager 时没有出现错误,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);
            }

但这不起作用.

推荐答案

我能够使用 Ian Brown 的 CookieManager 类启用 cookie:http://www.hccp.org/java-net-cookie-how-to.html

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

我把它重命名为IansCookieManager,设置一个类变量_CM = new IansCookieManager,现在很简单:

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);
            ...

这篇关于URLConnection 与 Cookies?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-20 11:47