当前位置: 代码迷 >> Android >> android 给url平添cookie
  详细解决方案

android 给url平添cookie

热度:35   发布时间:2016-05-01 18:33:37.0
android 给url添加cookie
前些天因为项目需要写了一个通过网络连接去服务端拿数据的方法,但是需要让程序添加上cookie,因为之前对cookie 没有怎么研究过(包括做web 那会也没有用过或者说很少用),所以

一时用起来不太会用。。结果百度google 了一把 发现要用cookieManager这个类,然后对这个类进行操作就行了!

String getCookie(Context context){CookieManager cookieManager = CookieManager.getInstance();String        cookie = cookieManager.getCookie("cookie");if(cookie != null){	return cookie;}else{cookie= “XXX”;cookieManager.setCookie("cookie", cookie);return cookie;}}


可以看到 我们只要设置在这里面然后再使用的时候我们在自己的httpconnection中添加就行了

URL  url = new URL(urlPath);HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();httpUrlConn.setRequestProperty("cookie", getCookie(context));


这样做 貌似是正确的。。当时我也是这么理解的。。但是很不幸的 是 。。。报错了。。

提示createInstance() must be instance called before getinstance()

很明显 我们必须要首先产生这个实例。。。结果查了一下API 需要在 getInstance()之前先
CookieSyncManager.createInstance(context);


这样之后就不会出错了。。createInstance 之后保证了我们的。。webkit在使用CookieManager的时候 使用的是同一个CookieManager并保证了 线程同步。。。。

这一点我们可以参看CookieSyncManager.createInstance(context);的源码。。。。。
  相关解决方案