技术联盟

Android WebView 与HttpClient 共用本地cookie问题

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

[html] view plaincopy在CODE上查看代码片派生到我的代码片

核心代码:
1. mainActivity.java

public void onCreate(Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.main_fragment, container, false);

mWebView = (WebView) v.findViewById(R.id.webview);
MyWebViewClient webviewClient = new MyWebViewClient();

mWebView.setWebViewClient(webviewClient);
WebSettings webset = mWebView.getSettings();
webset.setJavaScriptEnabled(true);
mWebView.loadUrl(Constants.TALKGROUP_URL);

return v;
}

private class MyWebViewClient extends WebViewClient {

@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);

IWLog.d(TAG, “onPageFinished() url is:”+url);
/* 将cookie保存起来*/
String c = CookieManager.getInstance().getCookie(url);
DataCenter.setCookie(c);
CookieSyncManager.getInstance().sync();
}

@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
IWLog.d(TAG, “onReceivedError() errorCode:” + errorCode+”—-failingUrl”+failingUrl);
super.onReceivedError(view, errorCode, description, failingUrl);
}

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
IWLog.d(TAG, “shouldOverrideUrlLoading() url:” + url);
return super.shouldOverrideUrlLoading(view, url);

}

}

2 DataCenter.java

public class DataCenter {

private static String cookies;

public static String getCookie() {
return cookies;
}

public static void setCookie(String cks) {
cookies = cks;
}

}

3 MyHttpClient.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.protocol.BasicHttpContext;

import com.petsea.data.DataCenter;
import com.petsea.data.NavigationUrl;

import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.util.Log;

public class MyHttpClient {

public static String TAG = “MyHttpClient”;

public void execute() {
RequestChatListTask task = new RequestChatListTask();
task.execute();
}

private class RequestChatListTask extends AsyncTask<Bitmap, Integer, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}

@Override
protected String doInBackground(Bitmap… params) {

BufferedReader in = null;
DefaultHttpClient httpclient;
BasicHttpContext localContext;
CookieStore cookieJar;
try {
httpclient = new DefaultHttpClient();
cookieJar = new BasicCookieStore();
localContext = new BasicHttpContext();

HttpGet httpget = new HttpGet();
httpget.setURI(new URI(NavigationUrl.CHAT_LIST_URL));//这里是你要请求的地址
String _cookie = DataCenter.getCookie();
if(_cookie !=null && !_cookie.equals(“”)){
String[] cookies = _cookie.split(“;”);
for(int i=0; i< cookies.length; i++){
String[] nvp = cookies[i].split(“=”);
BasicClientCookie c = new BasicClientCookie(nvp[0], nvp[1]);
//c.setVersion(0);
c.setDomain(“www.baidu.com”);//这里是自己的主机地址
cookieJar.addCookie(c);
}
}
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieJar);
HttpResponse response = httpclient.execute(httpget,localContext);

int code = response.getStatusLine().getStatusCode();
System.out.print(“code is=”+code);//返回200是正确的

in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer(“”);
String line = “”;
String NL = System.getProperty(“line.separator”);
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String page = sb.toString();
///System.out.println(page);
return page; //success

} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

return null;
}

@Override
protected void onProgressUpdate(Integer… values) {
super.onProgressUpdate(values);
}

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.i(TAG, “onPostExecute result is:” + result);

}

}
}

上面只是我工程的一部分代码,主要来说明问题的。不便把全部代码上传。
我也是调试了一阵才弄出来的。给大家推荐一个工具:WireShark 用于抓取网络包的,可以查看你的http请求以及返回,里面会显示到cookie的内容还有其它格式
下载地址 http://www.wireshark.org/download.html

Share this:

码字很辛苦,转载请注明来自技术联盟《Android WebView 与HttpClient 共用本地cookie问题》

评论