带有 Cookie 的 URL 连接?
我正在尝试创建一个支持 cookie 的 URLConnection。根据我可以使用的文档:
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
我无法让这段代码工作,然后我看到这仅适用于 API 9 (2.3)。但是,我在旧模拟器中使用 CookieManager 时没有收到错误,CookieManager 存在,但无法构造。有什么办法可以使其适用于早期版本吗?我尝试过:
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);
}
但这不起作用。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我能够使用 Ian Brown 的 CookieManager 类启用 cookie:
http://www.hccp.org/java-net-cookie-how -to.html
我将其重命名为 IansCookieManager,设置一个类变量 _CM = new IansCookieManager,现在就简单了:
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: