【问题标题】:Android Hybrid App + Volley, Cookies and WebViewAndroid Hybrid App + Volley、Cookies 和 WebView
【发布时间】:2016-08-30 07:03:02
【问题描述】:

我已经研究了超过 15 个小时来解决这个问题: 我正在构建一个混合应用程序,我使用 Volley 框架(本机视图)登录, 登录后,我立即获取响应标头,提取 Cookie 并将其保存到我的 sharedprefs 中。成功登录后,我有一个本机主屏幕,其中包含指向多个 Webview 的链接, 如何将登录时收到的 Cookie 传递到 Webview? 互联网上 90% 的 Answers 使用 CookieSyncManager,已弃用。 我也尝试了 java.net.CookieManager,但没有任何效果。

这是我的代码

  @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mWebView = new WebView(this);

    setContentView(mWebView);

    cookies = pref.getString(Const.COOKIE_KEY,"null");
    userID = pref.getString(Const.USER_ID_KEY,"null");
    mUrl = Const.PERFORMANCE_WEBVIEW_LINK + Const.USER_ID;
    String cookieText = Const.COOKIE_KEY + "=" + cookies;

    //Approach A Environment for the Cookies
    //Does not work
    cookieSync = CookieSyncManager.createInstance(this);
    cookieManager = CookieManager.getInstance();
    cookieManager.removeSessionCookie();
    cookieManager.setCookie(mUrl, cookieText);
    cookieSync.sync();

    SystemClock.sleep(10000);

    /*APPROACH B, sending the Cookies with header
      ##Did not Work##
    final Map<String, String> headers = new HashMap<>();

    Log.d("cookie", cookieText);
    headers.put("Cookie",cookieText);
    */

    if(cookies.equals("null") || userID.equals("null")) {
        Toast.makeText(PerformanceWebview.this, "Error", Toast.LENGTH_SHORT).show();
        //Logging Out
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
    }
    else {
        //mWebView.loadUrl(mUrl,headers);
        mWebView.loadUrl(mUrl);
        Toast.makeText(PerformanceWebview.this,cookieText, Toast.LENGTH_SHORT).show();
        Log.d("URL", "URL: " + mUrl);
    }


}

我还尝试将 WebClient 传递给 WebView 并覆盖它的 shouldOverrideURl 方法并将标头传递给它。 我做的另一种方法是使用 WebSettings 并传递一个 ChromeClient..

这里的答案似乎都不起作用

【问题讨论】:

  • 找到了一个解决方案:打电话给客户,告诉他们的后端开发人员允许一种方法避免 Cookie 并接受我的客户请求

标签: android cookies webview android-volley


【解决方案1】:

首先确保 Volley 使用 cookie:(参见 https://stackoverflow.com/a/21271347

// Make volley remember cookies

// Do this only once on app startup, and keep the reference to the cookiemanager.
// I'm saving it on an App class, but you can do something different.

App.cookieManager = new CookieManager();
CookieHandler.setDefault(App.cookieManager);

// Note, we are using the java.net.CookieManager above.

然后,例如在 Volley 中进行登录调用后,将 cookie 同步到 WebView:

// Sync cookies to webview
android.webkit.CookieManager webkitCookies = android.webkit.CookieManager.getInstance();

for (HttpCookie cookie : App.cookieManager.getCookieStore().getCookies()) {
    webkitCookies.setCookie(cookie.getDomain(), cookie.getName() + "=" + cookie.getValue());
}

if (Build.VERSION.SDK_INT >= 21) {
    webkitCookies.flush();
} else {
    CookieSyncManager.getInstance().sync();
}

【讨论】:

    【解决方案2】:
    class CookieStore_ implements CookieStore{
    /** this map may have null keys! */
    private final Map<URI, List<HttpCookie>> map = new HashMap<URI, List<HttpCookie>>();
    private android.webkit.CookieManager manager;
    
    public CookieStore_() {
        manager = android.webkit.CookieManager.getInstance();
    }
    
    public synchronized void add(URI uri, HttpCookie cookie) {
        if (cookie == null) {
            throw new NullPointerException("cookie == null");
        }
    
        uri = cookiesUri(uri);
        //add cookie to the CookieManager,be sure you have called
        //CookieSyncManager.createInstance(context) if your android version           
        //is lower than Lollipop
        manager.setCookie(uri.toString(),cookie.toString());
    
        List<HttpCookie> cookies = map.get(uri);
        if (cookies == null) {
            cookies = new ArrayList<HttpCookie>();
            map.put(uri, cookies);
        } else {
            cookies.remove(cookie);
        }
        cookies.add(cookie);
    }
    
    private URI cookiesUri(URI uri) {
        if (uri == null) {
            return null;
        }
        try {
            return new URI("http", uri.getHost(), null, null);
        } catch (URISyntaxException e) {
            return uri; // probably a URI with no host
        }
    }
    
    public synchronized List<HttpCookie> get(URI uri) {
        if (uri == null) {
            throw new NullPointerException("uri == null");
        }
    
        List<HttpCookie> result = new ArrayList<HttpCookie>();
    
        // get cookies associated with given URI. If none, returns an empty list
        List<HttpCookie> cookiesForUri = map.get(uri);
        if (cookiesForUri != null) {
            for (Iterator<HttpCookie> i = cookiesForUri.iterator(); i.hasNext(); ) {
                HttpCookie cookie = i.next();
                if (cookie.hasExpired()) {
                    i.remove(); // remove expired cookies
                } else {
                    result.add(cookie);
                }
            }
        }
    
        // get all cookies that domain matches the URI
        for (Map.Entry<URI, List<HttpCookie>> entry : map.entrySet()) {
            if (uri.equals(entry.getKey())) {
                continue; // skip the given URI; we've already handled it
            }
    
            List<HttpCookie> entryCookies = entry.getValue();
            for (Iterator<HttpCookie> i = entryCookies.iterator(); i.hasNext(); ) {
                HttpCookie cookie = i.next();
                if (!HttpCookie.domainMatches(cookie.getDomain(), uri.getHost())) {
                    continue;
                }
                if (cookie.hasExpired()) {
                    i.remove(); // remove expired cookies
                } else if (!result.contains(cookie)) {
                    result.add(cookie);
                }
            }
        }
    
        return Collections.unmodifiableList(result);
    }
    
    public synchronized List<HttpCookie> getCookies() {
        List<HttpCookie> result = new ArrayList<HttpCookie>();
        for (List<HttpCookie> list : map.values()) {
            for (Iterator<HttpCookie> i = list.iterator(); i.hasNext(); ) {
                HttpCookie cookie = i.next();
                if (cookie.hasExpired()) {
                    i.remove(); // remove expired cookies
                } else if (!result.contains(cookie)) {
                    result.add(cookie);
                }
            }
        }
        return Collections.unmodifiableList(result);
    }
    
    public synchronized List<URI> getURIs() {
        List<URI> result = new ArrayList<URI>(map.keySet());
        result.remove(null); // sigh
        return Collections.unmodifiableList(result);
    }
    
    public synchronized boolean remove(URI uri, HttpCookie cookie) {
        if (cookie == null) {
            throw new NullPointerException("cookie == null");
        }
    
        List<HttpCookie> cookies = map.get(cookiesUri(uri));
        if (cookies != null) {
            return cookies.remove(cookie);
        } else {
            return false;
        }
    }
    
    public synchronized boolean removeAll() {
        boolean result = !map.isEmpty();
        map.clear();
        return result;
    }
    
    public void clearCookies(){
        map.clear();
    }
    

    }

    这个类是从 CookieStoreImpl 复制的,并在其中添加了一个 android.webkit.CookieManager,当调用 add(URI uri, HttpCookie cookie) 时,将 cookie 添加到 cookieManager,然后当 webview 加载一个匹配的 url cookieManager,webview 将匹配的 cookie 添加到请求的标头中。

    下面是一个辅助类

    public class CookieUtil {
    private CookieManager manager;
    private CookieStore_ cookieStore_;
    private CookieSyncManager syncManager;
    private static CookieUtil cookieUtil;
    private boolean isInitialed = false;
    
    private CookieUtil(Context context) {
        manager = CookieManager.getInstance();
    
        if (!Util.hasLollipop()){
            syncManager = CookieSyncManager.createInstance(context);
        }
        cookieStore_ = new CookieStore_();
    }
    
    public void clearCookies(){
        if (manager.hasCookies()){
            if (Util.hasLollipop()){
                manager.removeAllCookies(null);
            }else {
                manager.removeAllCookie();
            }
        }
        cookieStore_.clearCookies();
    }
    
    public static CookieUtil getCookieUtil(Context context){
        if (cookieUtil == null)
            cookieUtil = new CookieUtil(context);
        return cookieUtil;
    }
    
    public void sync(){
        if (Util.hasLollipop()){
            manager.flush();
        }else {
            syncManager.sync();
        }
    }
    
    public void setThirdPartyCookieAcceptable(WebView webView){
        if (Util.hasLollipop()){
            manager.setAcceptThirdPartyCookies(webView,true);
        }
    }
    
    public void initCookieHandler(){
        if (isInitialed)
            return;
        isInitialed = true;
        CookieHandler.setDefault(new java.net.CookieManager(cookieStore_, CookiePolicy.ACCEPT_ORIGINAL_SERVER));
    }
    

    }

    如果您不需要将cookies保存到本地存储,您可以通过单行将volley cookies共享到webview

    CookieUtil.getCookieUtil(context).initCookieHandler();
    

    并且不要忘记在注销时调用 clearCookies()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-22
      • 1970-01-01
      • 1970-01-01
      • 2011-08-09
      • 2011-08-14
      • 1970-01-01
      • 2018-05-02
      相关资源
      最近更新 更多