将cookie从本机登录传递到webview

时间:2015-03-27 10:23:22

标签: android cookies android-webview httprequest android-cookiemanager

我正在关注this,以便将Cookie从原生代码共享到WebView。我有一个原生登录屏幕。成功登录后,我将CookieSyncManager中的cookie保存起来。当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 for login

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。

1 个答案:

答案 0 :(得分:1)

K7Ko's答案终于为我效劳了。但只有在我评论了这一行之后

cookieManager.removeSessionCookie();