1,在登陆成功的时候定义一个全局变量将cookie缓存起来
public static void saveCookie(DefaultHttpClient httpClient,Context content){
List<Cookie> cookies = httpClient.getCookieStore().getCookies();
Cookie cookie = null;
if (!cookies.isEmpty()) {
for (int i = 0; i < cookies.size(); i++) {
cookie = cookies.get(i);
}
}
ProtApplication.cookie=cookie;
}
其中ProtApplication.cookie为application中的一个全局变量
2,为webView请求之前设置cookie,具体方法如下
public void loadData(View v){
String requestUrl="http://172.36.0.102:8080/prot/main/announce2.0/announce_Launch.jsp";
testwv.getSettings().setJavaScriptEnabled(true);
Cookie sessionCookie = ProtApplication.cookie; //这里的cookie就是上面保存的cookie
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
String cookieString = sessionCookie.getName() + "=" + sessionCookie.getValue() + "; domain=" + sessionCookie.getDomain();
cookieManager.setCookie(requestUrl,cookieString);
cookieManager.setAcceptCookie(true);
testwv.loadUrl(requestUrl);
}