android webview同步,android httpclient与webview cookie同步

1,在登陆成功的时候定义一个全局变量将cookie缓存起来

public static void saveCookie(DefaultHttpClient httpClient,Context content){

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

}

注意:cookieString需要设置域名,loadUrl中的url与setCookie中的url应该保持一致

你可能感兴趣的:(android,webview同步)