本文系转载,原文地址:http://www.aichengxu.com/view/38894
利用HttpClient获得cookie,并在webview中使用的方法,有需要的朋友可以参考下。
在开发App中,经常遇到在webview中显示网站登录后的某些页面,这时候如果单纯的使用mWebView.loadUrl(web_url)方法时,仍然需要重新登陆web的系统,因此无法取得特定的页面,因此在上一次httpclient请求时,需要人为的保存下这一次网络连接的cookie,并将其保存为全局变量,方便webview的使用。
下面贴出httpclient中保存cookie的方法:
public static String HttpPostDataTestList(MyApplication myApplication,String url, long userId,
long studentUserId, String role, long pageNo) {
String result = "0";
try {
HttpParams params = new BasicHttpParams();
DefaultHttpClient httpclient = new DefaultHttpClient(params);
HttpPost httppost = new HttpPost(url);
JSONObject obj = new JSONObject();
obj.put("userId", userId);
obj.put("studentUserId", studentUserId);
obj.put("role", role);
obj.put("pageNo", pageNo);
httppost.setEntity(new StringEntity(obj.toString()));
HttpContext context = new BasicHttpContext();
CookieStore cookieStore = new BasicCookieStore();
context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpResponse response;
response = httpclient.execute(httppost, context);
// 检验状态码,如果成功接收数据
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
result = EntityUtils.toString(response.getEntity());// 返回json格式
List<Cookie> cookies=httpclient.getCookieStore().getCookies();
Log.e("cookies", "cookies"+cookies.size());
if (!cookies.isEmpty()) {
Log.e("chengong", "chenggong");
for (int i = cookies.size(); i > 0; i--) {
Cookie cookie = (Cookie) cookies.get(i - 1);
if (cookie.getName().equalsIgnoreCase("jsessionid")) {
// 使用一个常量来保存这个cookie,用于做session共享之用
myApplication.setCookie(cookie);
}
}
}
}
return result;
} catch (ClientProtocolException e) {
return result;
} catch (IOException e) {
return result;
} catch (Exception e) {
return result;
}
}
webview中设置cookie的方法:
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
MyApplication application = (MyApplication) getApplication();
Cookie sessionCookie = application.getCookie();
if (sessionCookie != null) {
Log.e("fail", "fail");
String cookieString = sessionCookie.getName() + "="
+ sessionCookie.getValue() + "; domain="
+ sessionCookie.getDomain();
cookieManager.setCookie(web_url, cookieString);
CookieSyncManager.getInstance().sync();
}
特别注意的是,这段代码需要添加在loadUrl方法前,否则没有效果。因为此时你已经加载了url.