2014-03-25 99 views
6

我必須在webview中加載url併發送一些cookie。爲什麼要做到這一點?Android - 如何通過cookie來加載與web視圖的網址?

我做下面的代碼..

CookieManager cookieManager; 

     CookieSyncManager.createInstance(PrivacyActivity.this); 
     cookieManager = CookieManager.getInstance(); 

     cookieManager.setCookie("param", "value"); 
     CookieSyncManager.getInstance().sync(); 

     WebSettings webSettings = wv.getSettings(); 
     webSettings.setJavaScriptEnabled(true); 
     webSettings.setBuiltInZoomControls(true); 
     wv.setWebViewClient(new WebViewClient() { 
     @Override 
     public boolean shouldOverrideUrlLoading(WebView view, String url) { 
     return super.shouldOverrideUrlLoading(view, url); 
     } 
     }); 
     wv.loadUrl("https://example.com"); 

,但沒有得到正確的結果。只是得到「https://example.com」就是這樣。 cookie不工作..

回答

6

我解決了問題,因爲,,,

 WebView webview = (WebView) this.findViewById(R.id.wv_file); 
     final WebSettings settings = webview.getSettings(); 
     settings.setJavaScriptEnabled(true); 
     settings.setAppCacheEnabled(true); 
     settings.setBuiltInZoomControls(true); 
     settings.setPluginState(WebSettings.PluginState.ON); 

     webview.setWebChromeClient(new WebChromeClient()); 

     CookieSyncManager.createInstance(ActivityName.this); 
     CookieManager cookieManager = CookieManager.getInstance(); 
     cookieManager.removeSessionCookie(); 
     String cookieString = "param=value"; 
     cookieManager.setCookie(domain_of_url("like http://abc-site.com"), cookieString); 
     CookieSyncManager.getInstance().sync(); 

     Map<String, String> abc = new HashMap<String, String>(); 
     abc.put("Cookie", cookieString); 
     webview.loadUrl("http://abc-site.com/a1/namedFolder/file", 
       abc); 
+5

CookieSyncManager現在已被棄用... –

+0

CookieSyncManager的替代品是什麼? 此外,我們是否需要手動添加Cookie?我們不能將所有cookie都傳遞給webview嗎? –

6

該解決方案對我的作品(只需在加載URL前添加cookie來CookieManager,這一切):

WebView webview = (WebView) findViewById(R.id.webview); 
... 
CookieManager.getInstance().setCookie("http://example.com/", "key=value"); 
webview.loadUrl("http://example.com/"); 
+0

謝謝Kata Lune。保存我的日子 – Santhana

+0

太棒了!像魅力一樣工作。 –

相關問題