2013-12-16 92 views
0

我有一個問題,餅乾,網絡視圖。 Webview不會加載從DefaultClient獲取的Cookie。 該代碼適用於早期版本的API 14,但不適用於更高版本。 我沒有錯誤,但由於缺少cookie,因此Webview中的頁面無法加載。設置Cookie WebView Android API 14

private CookieManager cookieManager; 
private class Connection extends AsyncTask<Oauth2Parameters,Void,HttpResponse> { 
     @Override 
     protected void onPreExecute() { 
      CookieSyncManager.createInstance(AuthorizeTokenFlow2.this); 
      cookieManager = CookieManager.getInstance();  
      SystemClock.sleep(500); 
     }    
     @Override 
     protected HttpResponse doInBackground(Oauth2Parameters... arg0) { 
      HttpResponse response=null; 
      try { 
       //Execute request with DefaultClientHTTP 
       response = getAuthentication(arg0[0].getAppId(),client);     
      } catch (Exception e) { 
       e.printStackTrace(); 
      }   
      return response; 
     }   
     @Override 
     protected void onPostExecute(HttpResponse result) { 
      try { 
       String html=Utility.extractBodyResponse(result);     
       managementCacheCookie(client); 
       webView = (WebView) findViewById(R.id.webView1);   
       WebSettings webSettings = webView.getSettings(); 
       webSettings.setJavaScriptEnabled(true); 
       webSettings.setBuiltInZoomControls(true); 
       webView.setWebViewClient(new WebViewClient(){ 
        @Override 
        public boolean shouldOverrideUrlLoading(WebView view, String url) { 
         view.loadUrl(url); 
         return true;     
        }      
       }); 
       webView.loadData(html, "text/html", null);   
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 

     } 
    } 
    private void managementCacheCookie(DefaultHttpClient client) 
    { 
     List<Cookie> cookies = client.getCookieStore().getCookies();   
     if (! cookies.isEmpty()){ 

      for (Cookie cookie : cookies){     
       Cookie sessionInfo = cookie;  
       String cookieString = sessionInfo.getName() + "=" + sessionInfo.getValue() + "; domain=" + sessionInfo.getDomain();    
       cookieManager.setCookie(sessionInfo.getDomain(), cookieString); 
      }   
      CookieSyncManager.getInstance().sync(); 
      } 
    } 
    private HttpResponse getAuthentication(String idDevice,DefaultHttpClient client) throws Exception {   
    URI website = new URI(Configuration.authorizeAddress); 
    HttpGet request = new HttpGet(); 
    request.addHeader("Authorization", "idDevice "+idDevice); 
    request.setURI(website); 
    HttpResponse response; 
    try{ 
     response = client.execute(request); 
    }catch(HttpHostConnectException htt) 
    { 
     htt.printStackTrace(); 
     throw htt; 
    }    
    return response; 
} 

感謝您的幫助

回答

0

我解決了,我用:

String cookieString = sessionInfo.getName() + "=" + sessionInfo.getValue(); 
cookieManager.setCookie(sessionInfo.getDomain(), cookieString); 

我刪除cookie中的域。我還補充說:

cookieManager.setAcceptCookie(true);