将 cookie 从本机登录传递到 webview
Pass cookies from native login to webview
我正在关注 this 从本机代码向 WebView
共享 cookie。我有一个本地登录屏幕。成功登录后,我将 cookie 保存在 CookieSyncManager
中。当 webview 加载时,我将这些 cookie 传递给它,这样登录屏幕就不会出现。
以下是我实施的内容:
public class MyApp extends Application {
public void onCreate() {
super.onCreate();
//Setup Cookie Manager and Persistence to disk
CookieSyncManager.createInstance(this);
CookieManager.getInstance().setAcceptCookie(true);
}
}
用于登录的 HttpRequest:
private void executeRequest(HttpUriRequest request, String url) {
DefaultHttpClient client = getDefaultClient(); // new DefaultHttpClient();
syncCookiesFromAppCookieManager(loginUrl, client);
HttpResponse httpResponse = null;
try {
httpResponse = client.execute(request);
} catch (IOException e1) {
e1.printStackTrace();
}
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = null;
try {
instream = entity.getContent();
} catch (IOException e1) {
e1.printStackTrace();
}
response = convertStreamToString(instream);
response = StringUtils.remove(response, "\n");
syncCookiesFromAppCookieManager(loginUrl, client);
// client.setCookieStore((org.apache.http.client.CookieStore) new PersistentCookieStore(context));
}
}
并且在 WebActivity 中:
CookieSyncManager.getInstance().sync();
webview.loadUrl(url);
但我又在 webView
上看到登录屏幕。即 cookie 没有被存储。
K7Ko's 答案终于对我有用了。但只有在我评论了
这一行之后
cookieManager.removeSessionCookie();
我正在关注 this 从本机代码向 WebView
共享 cookie。我有一个本地登录屏幕。成功登录后,我将 cookie 保存在 CookieSyncManager
中。当 webview 加载时,我将这些 cookie 传递给它,这样登录屏幕就不会出现。
以下是我实施的内容:
public class MyApp extends Application {
public void onCreate() {
super.onCreate();
//Setup Cookie Manager and Persistence to disk
CookieSyncManager.createInstance(this);
CookieManager.getInstance().setAcceptCookie(true);
}
}
用于登录的 HttpRequest:
private void executeRequest(HttpUriRequest request, String url) {
DefaultHttpClient client = getDefaultClient(); // new DefaultHttpClient();
syncCookiesFromAppCookieManager(loginUrl, client);
HttpResponse httpResponse = null;
try {
httpResponse = client.execute(request);
} catch (IOException e1) {
e1.printStackTrace();
}
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = null;
try {
instream = entity.getContent();
} catch (IOException e1) {
e1.printStackTrace();
}
response = convertStreamToString(instream);
response = StringUtils.remove(response, "\n");
syncCookiesFromAppCookieManager(loginUrl, client);
// client.setCookieStore((org.apache.http.client.CookieStore) new PersistentCookieStore(context));
}
}
并且在 WebActivity 中:
CookieSyncManager.getInstance().sync();
webview.loadUrl(url);
但我又在 webView
上看到登录屏幕。即 cookie 没有被存储。
K7Ko's 答案终于对我有用了。但只有在我评论了
这一行之后cookieManager.removeSessionCookie();