分享

Android WebView 与HttpClient 共用本地cookie问题

 quasiceo 2015-05-03
分类: android 2014-05-29 22:27 992人阅读 评论(0) 收藏 举报

我是为了解决:WebView 缓存下来的cookie可以用于HttpClient,因为我的HttpClient单独需要取一些数据,但是依赖于本地的cookie。如果没有cookie返回来的是登录页面

 

  1. <P><SPAN style="FONT-SIZE: 24px">核心代码:  
  2. 1. mainActivity.java</SPAN></P>  
  3. public void onCreate(Bundle savedInstanceState) {  
  4.         View v = inflater.inflate(R.layout.main_fragment, container, false);  
  5.           
  6.         mWebView = (WebView) v.findViewById(R.id.webview);  
  7.         MyWebViewClient webviewClient = new MyWebViewClient();  
  8.           
  9.     mWebView.setWebViewClient(webviewClient);  
  10.     WebSettings webset = mWebView.getSettings();  
  11.     webset.setJavaScriptEnabled(true);  
  12.     mWebView.loadUrl(Constants.TALKGROUP_URL);  
  13.       
  14.           
  15.         return v;  
  16.     }  
  17.   
  18. private class MyWebViewClient extends WebViewClient {  
  19.           
  20.         @Override  
  21.         public void onPageFinished(WebView view, String url) {  
  22.             super.onPageFinished(view, url);  
  23.               
  24.             IWLog.d(TAG, "onPageFinished() url is:"+url);  
  25.             /* 将cookie保存起来*/  
  26.             String c = CookieManager.getInstance().getCookie(url);  
  27.             DataCenter.setCookie(c);  
  28.             CookieSyncManager.getInstance().sync();  
  29.         }  
  30.           
  31.         @Override  
  32.         public void onReceivedError(WebView view, int errorCode,  
  33.                 String description, String failingUrl) {  
  34.             IWLog.d(TAG, "onReceivedError() errorCode:" + errorCode+"----failingUrl"+failingUrl);  
  35.             super.onReceivedError(view, errorCode, description, failingUrl);  
  36.         }  
  37.   
  38.   
  39.   
  40.   
  41.         @Override  
  42.         public boolean shouldOverrideUrlLoading(WebView view, String url) {  
  43.             IWLog.d(TAG, "shouldOverrideUrlLoading() url:" + url);  
  44.             return super.shouldOverrideUrlLoading(view, url);  
  45.               
  46.         }  
  47.   
  48.   
  49.     }  
  50. <P><SPAN style="FONT-SIZE: 24px">2 DataCenter.java</SPAN></P>  
  51. public class DataCenter {  
  52.   
  53.           
  54.     private static String cookies;  
  55.   
  56.     public static String getCookie() {  
  57.         return cookies;  
  58.     }  
  59.   
  60.     public static void setCookie(String cks) {  
  61.         cookies = cks;  
  62.     }  
  63.       
  64. }  
  65. <P><SPAN style="FONT-SIZE: 24px">3 MyHttpClient.java</SPAN></P>  
  66. import java.io.BufferedReader;  
  67. import java.io.IOException;  
  68. import java.io.InputStreamReader;  
  69. import java.net.URI;  
  70. import org.apache.http.HttpResponse;  
  71. import org.apache.http.client.CookieStore;  
  72. import org.apache.http.client.methods.HttpGet;  
  73. import org.apache.http.client.protocol.ClientContext;  
  74. import org.apache.http.impl.client.BasicCookieStore;  
  75. import org.apache.http.impl.client.DefaultHttpClient;  
  76. import org.apache.http.impl.cookie.BasicClientCookie;  
  77. import org.apache.http.protocol.BasicHttpContext;  
  78.   
  79. import com.petsea.data.DataCenter;  
  80. import com.petsea.data.NavigationUrl;  
  81.   
  82. import android.graphics.Bitmap;  
  83. import android.os.AsyncTask;  
  84. import android.util.Log;  
  85.   
  86. public class MyHttpClient {  
  87.       
  88.     public static String TAG = "MyHttpClient";  
  89.   
  90.     public void execute() {  
  91.         RequestChatListTask task = new RequestChatListTask();  
  92.         task.execute();  
  93.     }  
  94.   
  95.     private class RequestChatListTask extends AsyncTask<Bitmap, Integer, String> {  
  96.         @Override  
  97.         protected void onPreExecute() {  
  98.             super.onPreExecute();  
  99.         }  
  100.   
  101.         @Override  
  102.         protected String doInBackground(Bitmap... params) {  
  103.   
  104.             BufferedReader in = null;  
  105.             DefaultHttpClient httpclient;  
  106.             BasicHttpContext localContext;  
  107.             CookieStore cookieJar;  
  108.             try {  
  109.                 httpclient = new DefaultHttpClient();  
  110.                 cookieJar = new BasicCookieStore();  
  111.                 localContext = new BasicHttpContext();  
  112.                   
  113.                 HttpGet httpget = new HttpGet();  
  114.                 httpget.setURI(new URI(NavigationUrl.CHAT_LIST_URL));//这里是你要请求的地址  
  115.                 String _cookie = DataCenter.getCookie();  
  116.                  if(_cookie !=null && !_cookie.equals("")){  
  117.                      String[] cookies = _cookie.split(";");  
  118.                      for(int i=0; i< cookies.length; i++){  
  119.                          String[] nvp = cookies[i].split("=");  
  120.                          BasicClientCookie c = new BasicClientCookie(nvp[0], nvp[1]);  
  121.                          //c.setVersion(0);  
  122.                          c.setDomain("www.baidu.com");//这里是自己的主机地址  
  123.                          cookieJar.addCookie(c);  
  124.                      }  
  125.                 }  
  126.                 localContext.setAttribute(ClientContext.COOKIE_STORE, cookieJar);  
  127.                 HttpResponse response = httpclient.execute(httpget,localContext);  
  128.                   
  129.                 int code = response.getStatusLine().getStatusCode();  
  130.                 System.out.print("code is="+code);//返回200是正确的  
  131.                   
  132.                 in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));  
  133.                 StringBuffer sb = new StringBuffer("");  
  134.                 String line = "";  
  135.                 String NL = System.getProperty("line.separator");  
  136.                 while ((line = in.readLine()) != null) {  
  137.                     sb.append(line + NL);  
  138.                 }  
  139.                 in.close();  
  140.                 String page = sb.toString();  
  141.                 ///System.out.println(page);  
  142.                 return page; //success  
  143.                   
  144.             } catch (Exception e) {  
  145.                 e.printStackTrace();  
  146.             } finally {  
  147.                 if (in != null) {  
  148.                     try {  
  149.                         in.close();  
  150.                     } catch (IOException e) {  
  151.                         e.printStackTrace();  
  152.                     }  
  153.                 }  
  154.             }  
  155.   
  156.             return null;  
  157.         }  
  158.   
  159.         @Override  
  160.         protected void onProgressUpdate(Integer... values) {  
  161.             super.onProgressUpdate(values);  
  162.         }  
  163.   
  164.         @Override  
  165.         protected void onPostExecute(String result) {  
  166.             super.onPostExecute(result);  
  167.             Log.i(TAG, "onPostExecute result is:" + result);  
  168.   
  169.         }  
  170.   
  171.     }  
  172. }  
  173. <P><SPAN style="FONT-SIZE: 24px">上面只是我工程的一部分代码,主要来说明问题的。不便把全部代码上传。  
  174. 我也是调试了一阵才弄出来的。给大家推荐一个工具:WireShark 用于抓取网络包的,可以查看你的http请求以及返回,里面会显示到cookie的内容还有其它格式  
  175. 下载地址 http://www./download.html</SPAN></P>  



 

主题推荐
android webview cookie stringbuffer asynctask
猜你在找







    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多