您好,不确定我要问什么,因为我之前没有使用过Cookie。在我的应用程序中,我正在打开一个WebView,我们提交了一些数据,我想存储cookie,那样,当我关闭WebView(也要关闭app)并重新打开它时,它将使用存储的cookie。
我不太喜欢我的代码,因为我一直在关注示例。
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
ProgressBar progressBar = (ProgressBar)
findViewById(R.id.progress_bar);
progressBar.setIndeterminate(true);
progressBar.setVisibility(View.VISIBLE);
super.onPageStarted(view, url, favicon);
String cookieStr = CookieManager.getInstance().getCookie(url);
try {
storeCookies(url, cookieStr);
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
private void storeCookies(String url, String cookieString) throws URISyntaxException {
if (cookieString !=null && !cookieString.isEmpty()) {
URI uri = new URI(url);
List<HttpCookie> cookies = HttpCookie.parse(cookieString);
for (HttpCookie cookie : cookies) {
cookieStore = new CookieStore() {
@Override
public void add(URI uri, HttpCookie cookie) {
cookieStore.add(uri, cookie);
}
@Override
public List<HttpCookie> get(URI uri) {
return null;
}
@Override
public List<HttpCookie> getCookies() {
return null;
}
@Override
public List<URI> getURIs() {
return null;
}
@Override
public boolean remove(URI uri, HttpCookie cookie) {
return false;
}
@Override
public boolean removeAll() {
return false;
}
};
}
}
}
public void onPageFinished(WebView view, String url) {
ProgressBar progressBar = (ProgressBar)findViewById(R.id.progress_bar);
progressBar.setVisibility(View.GONE);
setURL(url);
}
});
}
答案 0 :(得分:0)
如果您要设置网站的Cookie,请遵循以下代码。
科特琳:
val cookieManager = CookieManager.getInstance()
cookieManager.setAcceptCookie(true)
cookieManager.setCookie("YOUR_WEBSITE_URL", "key=value")
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
val cookieSyncManager = CookieSyncManager.createInstance(this)
cookieSyncManager.sync()
}
Java:
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.setCookie("YOUR_WEBSITE_URL", "key=value");
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(this);
cookieSyncManager.sync();
}
将 YOUR_WEBSITE_URL 替换为您的网站url,并将 key = value 与值配对。希望这会有所帮助。