Android同步cookies webview和httpclient

标签 android cookies webview httpclient

我有一个登录 webview 和 httpclient,需要确认用户是否登录。 问题是 webview 和 httpclient 正在使用其他 cookie,因此 httpclient 无法获取 webview cookie。

我阅读了很多人的问题和教程,但没有任何效果。我读到的一些东西:

我在 Android 开发和其他网站上阅读了一些其他教程,但没有任何效果。

另一个帖子:https://stackoverflow.com/questions/28052461/syncing-webview-with-httpclient

问题是 cookie 不会同步。

我试过的东西:

        WebView webview;
        webview = (WebView) rootView.findViewById(R.id.webview);

        webview.setWebViewClient(new WebViewClient() {
            public void onPageFinished(WebView view, String url) {
                CookieSyncManager.getInstance().sync();

            }
        });
        webview.getSettings().setDomStorageEnabled(true);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.getSettings().setUseWideViewPort(true);
        webview.setWebChromeClient(new WebChromeClient());
        webview.loadUrl("http://www.klh-dev.com/lehava/lehava/system/mlogin.php");

还有一些:

   public String IsLoggedIn() {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    HttpClient client=new DefaultHttpClient();



                    HttpGet get=new HttpGet(url);
                     ResponseHandler<String> responseHandler = new BasicResponseHandler();
                    try {
                        response_str=client.execute(get,responseHandler);
                        System.out.println(response_str);
                    } catch (ClientProtocolException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    Cookie sessionInfo;
                    List<Cookie> cookies = client.getCookieStore().getCookies();

                    if (! cookies.isEmpty()){
                            CookieSyncManager.createInstance(getApplicationContext());
                            CookieManager cookieManager = CookieManager.getInstance();

                            for(Cookie cookie : cookies){
                                    sessionInfo = cookie;
                                    String cookieString = sessionInfo.getName() + "=" + sessionInfo.getValue() + "; domain=" + sessionInfo.getDomain();
                                    cookieManager.setCookie(URLn, cookieString);
                                    CookieSyncManager.getInstance().sync();
                            }
                    }
                }
            }).start();
            return response_str;
   }

*httpget返回1或0

我想从 webview 获取 cookie 并在我的 httpclient 请求中使用它们

编辑(添加了 darpan 的回答):

    public static BasicCookieStore getCookieStore(String cookies, String domain) {
        String[] cookieValues = cookies.split(";");
        BasicCookieStore cs = new BasicCookieStore();

        BasicClientCookie cookie;
        for (int i = 0; i < cookieValues.length; i++) {
            String[] split = cookieValues[i].split("=");
            if (split.length == 2)
                cookie = new BasicClientCookie(split[0], split[1]);
            else
                cookie = new BasicClientCookie(split[0], null);

            cookie.setDomain(domain);
            cs.addCookie(cookie);
        }
        return cs;

        }

    public String IsLoggedIn() {
        new Thread(new Runnable() {
            @Override
            public void run() {




                     String cookies = CookieManager.getInstance().getCookie("http://klh-dev.com/lehava/lehava/system/isloggedin.php");
                     BasicCookieStore lCS = getCookieStore(cookies, "klh-dev.com");

                     HttpContext localContext = new BasicHttpContext();
                     DefaultHttpClient httpclient = new DefaultHttpClient();
                     httpclient.setCookieStore(lCS);
                     localContext.setAttribute(ClientContext.COOKIE_STORE, lCS);

                HttpGet get=new HttpGet("http://klh-dev.com/lehava/lehava/system/isloggedin.php");
                 ResponseHandler<String> responseHandler = new BasicResponseHandler();



                try {
                    result=httpclient.execute(get,localContext);
                    response_str = EntityUtils.toString(result.getEntity());
                    System.out.println(response_str);
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }


            }
        }).start();
        return response_str;
    }
}

EDIT2:终于成功了!! 这是我的代码:

public static String IsLoggedIn() {
    new Thread(new Runnable() {
        @Override
        public void run() {
                 String cookies = CookieManager.getInstance().getCookie(getUrl);
                 BasicCookieStore lCS = getCookieStore(cookies, "klh-dev.com");

                 HttpContext localContext = new BasicHttpContext();
                 DefaultHttpClient httpclient = new DefaultHttpClient();
                 httpclient.setCookieStore(lCS);
                 localContext.setAttribute(ClientContext.COOKIE_STORE, lCS);

            HttpGet get = new HttpGet("http://klh-dev.com/lehava/lehava/system/isloggedin.php");


            try {
                result=httpclient.execute(get,localContext);
                response_str = EntityUtils.toString(result.getEntity());
                System.out.println(response_str);
                ((MainActivity) getContext).UpdateMenu();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }).start();
    return response_str;
}

关于 getUrl 变量。 我必须像这样设置一个全局变量:

private static String getUrl;

public String getUrl() {
    return getUrl;
}  

我必须在每个 fragment 上添加 onPageFinished:getUrl = view.getUrl();

谢谢。

最佳答案

在您的代码中,您所做的似乎与您想做的相反(从 Webview 获取 cookie 并在 HttpClient 中设置)

编辑:来自 Mor Haviv 的回答 -

您需要定义一个全局变量来存储 View 中的当前 url -

private static String getUrl;

从 webview 获取 cookie -

@Override
public void onPageFinished(WebView view, String url){
    getUrl = view.getUrl();
    String cookies = CookieManager.getInstance().getCookie(getUrl);
    Log.d(TAG, "All the cookies in a string:" + cookies);
}

Reference for above code

在您的 HttpClient 中设置这个名为“cookies”的字符串 -

public static BasicCookieStore getCookieStore(String cookies, String domain) {
String[] cookieValues = cookies.split(";");
BasicCookieStore cs = new BasicCookieStore();

BasicClientCookie cookie;
for (int i = 0; i < cookieValues.length; i++) {
    String[] split = cookieValues[i].split("=");
    if (split.length == 2)
        cookie = new BasicClientCookie(split[0], split[1]);
    else
        cookie = new BasicClientCookie(split[0], null);

    cookie.setDomain(domain);
    cs.addCookie(cookie);
}
return cs;

}
 //And, use the same 'getUrl' here to fetch the cookie. (Haviv's addition)
 String cookies = CookieManager.getInstance().getCookie(getUrl);
 BasicCookieStore lCS = getCookieStore(cookies, YOUR_APP_DOMAIN);

 HttpContext localContext = new BasicHttpContext();
 DefaultHttpClient httpclient = new DefaultHttpClient();
 httpclient.setCookieStore(lCS);
 localContext.setAttribute(ClientContext.COOKIE_STORE, lCS);

附言 - 将您的应用程序域置于“YOUR_APP_DOMAIN” 而且,我无法检查代码,因为我没有您的域。

Reference for above code

关于Android同步cookies webview和httpclient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26798500/

相关文章:

android - 无法居中列小部件

java - 在 getSupportLoaderManager() 中使用 'this' 给我一条错误消息

javascript - 存储超过 4096 字节的数组一周

javascript - Ember.js - 设置启用仅 HTTP cookie?

android - WebView 中的客户端证书身份验证

Android getLastKnownLocation(LocationManager.GPS_PROVIDER) 返回 null

android - 同一对象数组中的数组中的json数组?

angularjs - .net Core MVC : X-SRF-TOKEN not accepted, 400 返回

android - 有没有办法在我的 Android 应用程序中以编程方式设置代理服务器?

android - 首次启动应用程序时 WebView 无法登录