ANDROID:在Webview和httpclient之间共享会话
作者:互联网
我实际上在WebView中记录了会话.
但我也使用httpclient来发送和从网络获取数据.我在互联网上看到,无法获取WebView的内容,因此我需要使用我的httpclient从Web服务获取数据.
问题是这个webservice使用会话…而我的会话在我的WebView中,所以httpclient没有它,我无法访问webservice的内容.
我看到很多关于这个问题的帖子,但我不明白解决方案.
这是我在onPageStarted上做的:
CookieManager mgr = CookieManager.getInstance();
Log.i( "URL", url );
Log.i("Cookie",mgr.getCookie("mywebsite.com"));
String cookie_string = mgr.getCookie("mywebsite.com");
if(cookie_string.length() > 1) {
Data.instance().getPref().edit().putString("cookie",cookie_string).commit();
}
我看到我有这样的东西,所以我希望那些也包括会话:
(我删除号码)
__utma=......(number)......;
__utmc=number;
__utmz=number.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none);
wt3_eid=%number%number;
wt3_sid=%number
然后我不知道该怎么做才能在我的httpclient中设置这个cookie.我尝试了,没有成功:
HttpClient client = new DefaultHttpClient();
BasicCookieStore cookieStore = new BasicCookieStore();
String login_cookie_string = Data.instance().getPref().getString("cookie", "");
String[] cookie_parts = null;
if(login_cookie_string.length()> 0)
{
//debug_view.setText(login_cookie_string);
Log.d("COOKIE", login_cookie_string);
cookie_parts = login_cookie_string.split(";");
for(int t=0;t < cookie_parts.length;t++)
{
String[] cookieContent = cookie_parts[t].split("=");
Cookie login_cookie = new BasicClientCookie(cookieContent[0],cookieContent[1]);
((BasicClientCookie) login_cookie).setDomain("mywebsite.com");
cookieStore.addCookie(login_cookie);
}
}
((AbstractHttpClient) client).setCookieStore(cookieStore);
解决方法:
所以,这就是我所做的,它对我有用 –
HttpRequestBase request = new HttpGet(uri);
request.addHeader("Cookie", getCookieFromAppCookieManager(uri.toString()));
现在,getCookieFromAppCookieManager的实现如下 –
该方法从应用程序CookieManager获取给定URL的cookie.应用程序CookieManager管理应用程序的WebView实例使用的cookie.
@param url the URL for which the cookies are requested
@return value the cookies as a string, using the format of the 'Cookie' HTTP request header
@throws MalformedURLException
public static String getCookieFromAppCookieManager(String url) throws MalformedURLException {
CookieManager cookieManager = CookieManager.getInstance();
if (cookieManager == null)
return null;
String rawCookieHeader = null;
URL parsedURL = new URL(url);
// Extract Set-Cookie header value from Android app CookieManager for this URL
rawCookieHeader = cookieManager.getCookie(parsedURL.getHost());
if (rawCookieHeader == null)
return null;
return rawCookieHeader;
}
标签:android,webview,httpclient,session-cookies 来源: https://codeday.me/bug/20190926/1821101.html