下面列出了android.webkit.CookieManager#setCookie ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public String get_location(){
String newloc = "0,0";
//Checking for location permissions
if (ASWP_LOCATION && (Build.VERSION.SDK_INT < 23 || check_permission(1))) {
GPSTrack gps;
gps = new GPSTrack(MainActivity.this);
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
if (gps.canGetLocation()) {
if (latitude != 0 || longitude != 0) {
if(true_online) {
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.setCookie(ASWV_URL, "lat=" + latitude);
cookieManager.setCookie(ASWV_URL, "long=" + longitude);
}
//Log.w("New Updated Location:", latitude + "," + longitude); //enable to test dummy latitude and longitude
newloc = latitude+","+longitude;
} else {
Log.w("New Updated Location:", "NULL");
}
} else {
show_notification(1, 1);
Log.w("New Updated Location:", "FAIL");
}
}
return newloc;
}
@Override
public void setCookieFromCookieStore(Context context, String url, List<Cookie> cks) {
CookieUtils.syncCookie(context);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
if (!ListUtils.isNullOrContainEmpty(cks)) {
for (int i = 0; i < cks.size(); i++) {
Cookie cookie = cks.get(i);
String cookieStr = cookie.getName() + "=" + cookie.getValue() + ";"
+ "expiry=" + cookie.getExpiryDate() + ";"
+ "domain=" + cookie.getDomain() + ";"
+ "path=/";
// ZogUtils.printError(WebFragment.class, "set cookie string:" + cookieStr);
cookieManager.setCookie(url, cookieStr);//cookieStr是在HttpClient中获得的cookie
}
}
}
public static void setCookieFromCookieStore(Context context, String url) {
syncCookie(context);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
List<Cookie> cookies = getCookies(context);
Log.e("cookies", "cookies.size:" + cookies.size());
if (!cookies.isEmpty()) {
for (int i = 0; i < cookies.size(); i++) {
Cookie cookie = cookies.get(i);
String cookieStr = cookie.getName() + "=" + cookie.getValue() + ";"
+ "expiry=" + cookie.getExpiryDate() + ";"
+ "domain=" + cookie.getDomain() + ";"
+ "path=/";
cookieManager.setCookie(url, cookieStr);//cookies是在HttpClient中获得的cookie
}
}
}
private void syncCookie(String url) {
CookieManager cookieManager = TyWebViewCookie.getInstance();
if (cookieManager == null) {
return;
}
List<Cookie> cookies = PersistentCookieStore.getInstance().getCookies();
for (int i = 0; i < cookies.size(); i++) {
Cookie cookie = cookies.get(i);
String value = cookie.name() + "=" + cookie.value();
cookieManager.setCookie(url, value);
}
TyWebViewCookie.sync();
}
private static void clearCookiesForDomain(Context context, String domain) {
// This is to work around a bug where CookieManager may fail to instantiate if CookieSyncManager
// has never been created.
CookieSyncManager syncManager = CookieSyncManager.createInstance(context);
syncManager.sync();
CookieManager cookieManager = CookieManager.getInstance();
String cookies = cookieManager.getCookie(domain);
if (cookies == null) {
return;
}
String[] splitCookies = cookies.split(";");
for (String cookie : splitCookies) {
String[] cookieParts = cookie.split("=");
if (cookieParts.length > 0) {
String newCookie = cookieParts[0].trim() + "=;expires=Sat, 1 Jan 2000 00:00:01 UTC;";
cookieManager.setCookie(domain, newCookie);
}
}
cookieManager.removeExpiredCookie();
}
private static void clearCookiesForDomain(Context context, String domain) {
// This is to work around a bug where CookieManager may fail to instantiate if
// CookieSyncManager has never been created.
CookieSyncManager syncManager = CookieSyncManager.createInstance(context);
syncManager.sync();
CookieManager cookieManager = CookieManager.getInstance();
String cookies = cookieManager.getCookie(domain);
if (cookies == null) {
return;
}
String[] splitCookies = cookies.split(";");
for (String cookie : splitCookies) {
String[] cookieParts = cookie.split("=");
if (cookieParts.length > 0) {
String newCookie = cookieParts[0].trim() +
"=;expires=Sat, 1 Jan 2000 00:00:01 UTC;";
cookieManager.setCookie(domain, newCookie);
}
}
cookieManager.removeExpiredCookie();
}
private void setCookie(Context context, String domain, String sessionCookie) {
CookieSyncManager.createInstance(context);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
if (sessionCookie != null) {
// delete old cookies
cookieManager.removeSessionCookie();
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
cookieManager.setCookie(domain, sessionCookie);
CookieSyncManager.createInstance(context);
CookieSyncManager.getInstance().sync();
}
private static void clearCookiesForDomain(Context context, String domain) {
// This is to work around a bug where CookieManager may fail to instantiate if CookieSyncManager
// has never been created.
CookieSyncManager syncManager = CookieSyncManager.createInstance(context);
syncManager.sync();
CookieManager cookieManager = CookieManager.getInstance();
String cookies = cookieManager.getCookie(domain);
if (cookies == null) {
return;
}
String[] splitCookies = cookies.split(";");
for (String cookie : splitCookies) {
String[] cookieParts = cookie.split("=");
if (cookieParts.length > 0) {
String newCookie = cookieParts[0].trim() + "=;expires=Sat, 1 Jan 2000 00:00:01 UTC;";
cookieManager.setCookie(domain, newCookie);
}
}
cookieManager.removeExpiredCookie();
}
protected void sendResponseMessage(HttpResponse response) {
super.sendResponseMessage(response);
Header[] headers = response.getHeaders("Set-Cookie");
if (headers != null && headers.length > 0) {
CookieSyncManager.createInstance(this.val$context).sync();
CookieManager instance = CookieManager.getInstance();
instance.setAcceptCookie(true);
instance.removeSessionCookie();
String mm = "";
for (Header header : headers) {
String[] split = header.toString().split("Set-Cookie:");
EALogger.i("正式登录", "split[1]===>" + split[1]);
instance.setCookie(Constants.THIRDLOGIN, split[1]);
int index = split[1].indexOf(";");
if (TextUtils.isEmpty(mm)) {
mm = split[1].substring(index + 1);
EALogger.i("正式登录", "mm===>" + mm);
}
}
EALogger.i("正式登录", "split[1222]===>COOKIE_DEVICE_ID=" + LemallPlatform.getInstance().uuid + ";" + mm);
instance.setCookie(Constants.THIRDLOGIN, "COOKIE_DEVICE_ID=" + LemallPlatform.getInstance().uuid + ";" + mm);
instance.setCookie(Constants.THIRDLOGIN, "COOKIE_APP_ID=" + LemallPlatform.getInstance().getmAppInfo().getId() + ";" + mm);
CookieSyncManager.getInstance().sync();
this.val$iLetvBrideg.reLoadWebUrl();
}
}
private static void clearCookiesForDomain(Context context, String domain) {
// This is to work around a bug where CookieManager may fail to instantiate if CookieSyncManager
// has never been created.
CookieSyncManager syncManager = CookieSyncManager.createInstance(context);
syncManager.sync();
CookieManager cookieManager = CookieManager.getInstance();
String cookies = cookieManager.getCookie(domain);
if (cookies == null) {
return;
}
String[] splitCookies = cookies.split(";");
for (String cookie : splitCookies) {
String[] cookieParts = cookie.split("=");
if (cookieParts.length > 0) {
String newCookie = cookieParts[0].trim() + "=;expires=Sat, 1 Jan 2000 00:00:01 UTC;";
cookieManager.setCookie(domain, newCookie);
}
}
cookieManager.removeExpiredCookie();
}
private static void clearCookiesForDomain(Context context, String domain) {
// This is to work around a bug where CookieManager may fail to instantiate if CookieSyncManager
// has never been created.
CookieSyncManager syncManager = CookieSyncManager.createInstance(context);
syncManager.sync();
CookieManager cookieManager = CookieManager.getInstance();
String cookies = cookieManager.getCookie(domain);
if (cookies == null) {
return;
}
String[] splitCookies = cookies.split(";");
for (String cookie : splitCookies) {
String[] cookieParts = cookie.split("=");
if (cookieParts.length > 0) {
String newCookie = cookieParts[0].trim() + "=;expires=Sat, 1 Jan 2000 00:00:01 UTC;";
cookieManager.setCookie(domain, newCookie);
}
}
cookieManager.removeExpiredCookie();
}
public static void a(Context context, String str, String str2, String str3, String str4) {
if (!TextUtils.isEmpty(str)) {
CookieSyncManager.createInstance(context);
CookieManager instance = CookieManager.getInstance();
instance.setAcceptCookie(true);
String str5 = null;
if (Uri.parse(str).getHost().toLowerCase().endsWith(".qq.com")) {
str5 = ".qq.com";
}
instance.setCookie(str, b("logintype", "MOBILEQ", str5));
instance.setCookie(str, b("qopenid", str2, str5));
instance.setCookie(str, b("qaccesstoken", str3, str5));
instance.setCookie(str, b("openappid", str4, str5));
CookieSyncManager.getInstance().sync();
}
}
private static void clearCookiesForDomain(Context context, String domain) {
// This is to work around a bug where CookieManager may fail to instantiate if CookieSyncManager
// has never been created.
CookieSyncManager syncManager = CookieSyncManager.createInstance(context);
syncManager.sync();
CookieManager cookieManager = CookieManager.getInstance();
String cookies = cookieManager.getCookie(domain);
if (cookies == null) {
return;
}
String[] splitCookies = cookies.split(";");
for (String cookie : splitCookies) {
String[] cookieParts = cookie.split("=");
if (cookieParts.length > 0) {
String newCookie = cookieParts[0].trim() + "=;expires=Sat, 1 Jan 2000 00:00:01 UTC;";
cookieManager.setCookie(domain, newCookie);
}
}
cookieManager.removeExpiredCookie();
}
@Override
public boolean setCookie(String url, List<String> cookies) {
if (!TextUtils.isEmpty(url) && cookies != null && cookies.size() > 0) {
CookieManager cookieManager = CookieManager.getInstance();
for (String cookie : cookies) {
cookieManager.setCookie(url, cookie);
}
return true;
}
return false;
}
private void init() {
WebSettings settings = getSettings();
settings.setBuiltInZoomControls(false);
settings.setSupportZoom(false);
settings.setJavaScriptEnabled(true);
settings.setAllowFileAccess(true);
settings.setSupportMultipleWindows(false);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setDomStorageEnabled(true);
settings.setCacheMode(WebSettings.LOAD_DEFAULT);
settings.setUseWideViewPort(true);
if (Build.VERSION.SDK_INT > 6) {
settings.setAppCacheEnabled(true);
settings.setLoadWithOverviewMode(true);
}
String path = getContext().getFilesDir().getPath();
settings.setGeolocationEnabled(true);
settings.setGeolocationDatabasePath(path);
settings.setDomStorageEnabled(true);
this.basicUA = settings.getUserAgentString() + " kanqiu/7.05.6303/7059";
setBackgroundColor(0);
initWebViewClient();
setWebChromeClient(new HuPuChromeClient());
try {
if (SettingPrefUtils.isLogin()) {
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setCookie("http://bbs.mobileapi.hupu.com", "u=" + SettingPrefUtils.getCookies());
cookieManager.setCookie("http://bbs.mobileapi.hupu.com", "_gamesu=" + URLEncoder.encode(SettingPrefUtils.getToken(), "utf-8"));
cookieManager.setCookie("http://bbs.mobileapi.hupu.com", "_inKanqiuApp=1");
cookieManager.setCookie("http://bbs.mobileapi.hupu.com", "_kanqiu=1");
CookieSyncManager.getInstance().sync();
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public boolean setCookie(String url, List<String> cookies) {
if (!TextUtils.isEmpty(url) && cookies != null && cookies.size() > 0) {
CookieManager cookieManager = CookieManager.getInstance();
for (String cookie : cookies) {
cookieManager.setCookie(url, cookie);
}
return true;
}
return false;
}
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// http://stackoverflow.com/questions/32284642/how-to-handle-an-uncatched-exception
CookieManager cookieManager = CookieManager.getInstance();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
cookieManager.flush();
cookieManager.removeAllCookies(null);
cookieManager.removeSessionCookies(null);
} else {
CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(this);
cookieSyncManager.startSync();
cookieManager.removeAllCookie();
cookieManager.removeSessionCookie();
cookieSyncManager.stopSync();
}
// Copy cookies from okhttp cookie store to CookieManager
url = EhUrl.getUConfigUrl();
EhCookieStore store = EhApplication.getEhCookieStore(this);
for (Cookie cookie : store.getCookies(HttpUrl.parse(url))) {
cookieManager.setCookie(url, cookie.toString());
}
setContentView(R.layout.activity_u_config);
setNavigationIcon(R.drawable.v_arrow_left_dark_x24);
webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new UConfigWebViewClient());
webView.setWebChromeClient(new DialogWebChromeClient(this));
webView.loadUrl(url);
progress = (ProgressView) findViewById(R.id.progress);
Snackbar.make(webView, R.string.apply_tip, Snackbar.LENGTH_LONG).show();
}
public static void setGameTokenCookie(Context context, String token) {
CookieSyncManager syncManger = CookieSyncManager.createInstance(context);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.setCookie("http://api.game.letvstore.com", "sso_tk=" + token);
syncManger.sync();
LogInfo.log("wlx", "game cookie = " + cookieManager.getCookie("http://api.game.letvstore.com"));
}
/**
* Synchronize the uuid2 cookie to the Webview Cookie Jar
* This is only done if there is no present cookie.
* @param headers headers to extract cookies from for syncing
*/
@SuppressWarnings("deprecation")
public static void cookieSync(Map<String, List<String>> headers) {
if (headers == null || headers.isEmpty()) return;
CookieManager cm = CookieManager.getInstance();
if (cm == null) {
// Logger.i(Logger.LOGTAG, "Unable to find a CookieManager");
return;
}
try {
String existingUUID = getExistingANUUID();
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
String key = entry.getKey();
// Only "Set-cookie" and "Set-cookie2" pair will be parsed
if (key != null && (key.equalsIgnoreCase(VERSION_ZERO_HEADER)
|| key.equalsIgnoreCase(VERSION_ONE_HEADER))) {
for (String cookieStr : entry.getValue()) {
if (!TextUtils.isEmpty(cookieStr) && cookieStr.contains(Settings.AN_UUID)) {
// pass uuid2 to WebView Cookie jar if it's empty or outdated
if ((existingUUID == null || !cookieStr.contains(existingUUID))) {
cm.setCookie(Settings.getCookieDomain(), cookieStr);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
// CookieSyncManager is deprecated in API 21 Lollipop
CookieSyncManager csm = CookieSyncManager.getInstance();
if (csm == null) {
Clog.i(Clog.httpRespLogTag,"Unable to find a CookieSyncManager");
return;
}
csm.sync();
} else {
cm.flush();
}
}
}
}
}
}
} catch (IllegalStateException ise) {
} catch (Exception e) {
}
}
/**
* Synchronize the uuid2 cookie to the Webview Cookie Jar
* This is only done if there is no present cookie.
*
* @param headers headers to extract cookies from for syncing
*/
@SuppressWarnings("deprecation")
private void httpCookieSync(Map<String, List<String>> headers) {
if (headers == null || headers.isEmpty()) return;
CookieManager cm = CookieManager.getInstance();
if (cm == null) {
LogUtil.i("PrebidNewAPI", "Unable to find a CookieManager");
return;
}
try {
String existingUUID = getExistingCookie();
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
String key = entry.getKey();
// Only "Set-cookie" and "Set-cookie2" pair will be parsed
if (key != null && (key.equalsIgnoreCase(PrebidServerSettings.VERSION_ZERO_HEADER)
|| key.equalsIgnoreCase(PrebidServerSettings.VERSION_ONE_HEADER))) {
for (String cookieStr : entry.getValue()) {
if (!TextUtils.isEmpty(cookieStr) && cookieStr.contains(PrebidServerSettings.AN_UUID)) {
// pass uuid2 to WebView Cookie jar if it's empty or outdated
if (existingUUID == null || !cookieStr.contains(existingUUID)) {
cm.setCookie(PrebidServerSettings.COOKIE_DOMAIN, cookieStr);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
// CookieSyncManager is deprecated in API 21 Lollipop
CookieSyncManager.createInstance(PrebidMobile.getApplicationContext());
CookieSyncManager csm = CookieSyncManager.getInstance();
if (csm == null) {
LogUtil.i("Unable to find a CookieSyncManager");
return;
}
csm.sync();
} else {
cm.flush();
}
}
}
}
}
}
} catch (IllegalStateException ise) {
} catch (Exception e) {
}
}