1. 程式人生 > >Android菜鳥學習筆記(WebView載入html頁面,頁面提交資料問題)

Android菜鳥學習筆記(WebView載入html頁面,頁面提交資料問題)

在開發過程中,有一個問卷調查功能,問卷是url用webView載入html頁面出來,在html頁面提交時發現session沒和webview的同步導致提交失敗,這個問題困擾了我很久,後來在前輩的共同研究下,終於找到辦法:獲取html頁面提交的url,然後對url做一次cookie同步操作,然後再提交就可以了。

//cookie同步方法:
    public static void synCookies(Context context, String url){

DefaultHttpClient httpclient2 = (DefaultHttpClient)RequestUtils.getHttpClient().getHttpClient();
//CookieStore cookieStores =(CookieStore)CloudUtils.getHttpClient().getHttpContext().getAttribute(ClientContext.COOKIE_STORE);
List<Cookie> cookies = httpclient2.getCookieStore().getCookies();  
if (!cookies.isEmpty()){  
   CookieSyncManager.createInstance(context);  
   CookieManager cookieManager = CookieManager.getInstance();  
       //sync all the cookies in the httpclient with the webview by generating cookie string  
   for (Cookie cookie : cookies){  
       String cookieString = cookie.getName() + "=" + cookie.getValue() + "; domain=" + cookie.getDomain();  
       cookieManager.setCookie(url, cookieString);  
       CookieSyncManager.getInstance().sync();  
   }  
}

}

//form表單獲取url設定同步cookie

webView.setWebViewClient(new WebViewClient() {
    public WebResourceResponse shouldInterceptRequest(WebView view, String url)
            { 
    //  重寫此方法表明點選網頁裡面的連結還是在當前的webview裡跳轉,不跳到瀏覽器那邊
    AppConfig.synCookies(QuestionnaireDetailActivity.this,url);
return null;
            }
});