After logging in with WebView, when I call HttpClient... The opposite is also true.
In Android, WebView and HttpClient seem to be treated as separate browsers.
This matter has been explained here and there.
[Android]WebView, Share Session with HTTPClient
HttpClient and WebView Integration
However, I created a class that only synchronizes so that I don't have to think about anything further. If you like, please.
[code lang="java" light="true"] package your.package;
import java.util.List;
import org.apache.http.client.CookieStore; import org.apache.http.cookie.Cookie; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.cookie.BasicClientCookie;
import android.webkit.CookieManager; import android.webkit.CookieSyncManager;
/** * HttpClient, class for synchronizing sessions between WebViews */ public class SessionSync {
Specify the domain from which the COOKIE will be sent
private static final String YOUR_DOMAIN = "your.domain";
COOKIE retrieval domain (with a . to cover subdomains)
private static final String COOKIE_DOMAIN = "." + YOUR_DOMAIN;
URL to send COOKIE
private static final String COOKIE_URL = "http://" + YOUR_DOMAIN;
Specify the parameter name to store the session ID
This is an example of PHP
private static final String SESSID = "PHPSESSID";
/**
* Sync the session ID on the HttpClient side to the WebView
*
* @param HttpClient to synchronize the session
*/
public static void httpClient2WebView(DefaultHttpClient httpClient) {
CookieStore store = httpClient.getCookieStore();
List<Cookie> cookies = store.getCookies();
CookieManager cookieManager = CookieManager.getInstance();
for (Cookie cookie : cookies) {
if (cookie.getDomain().indexOf(COOKIE_DOMAIN) < 0) {
continue;
}
if (! SESSID.equals(cookie.getName())) {
continue;
}
If you delete it here, the cookie you set at the time of sync will also be
Deletion is not allowed because it may disappear
// cookieManager.removeSessionCookie();
String cookieStr = cookie.getName() + "=" + cookie.getValue();
cookieManager.setCookie(COOKIE_DOMAIN, cookieStr);
CookieSyncManager.getInstance().sync();
}
}
/**
* Sync the session ID on the WebView side to the HttpClient
*
* @param HttpClient to synchronize the session
*/
public static void webView2HttpClient(DefaultHttpClient httpClient) {
String cookie = CookieManager.getInstance().getCookie(COOKIE_URL);
String[] cookies = cookie.split("; ");
for (String keyValue : cookies) {
keyValue = keyValue.trim();
String[] cookieSet = keyValue.split("=");
String key = cookieSet[0];
String value = cookieSet[1];
if (! SESSID.equals(key)) {
continue;
}
BasicClientCookie bCookie = new BasicClientCookie(key, value);
bCookie.setDomain(COOKIE_DOMAIN);
bCookie.setPath("/");
CookieStore store = httpClient.getCookieStore();
store.addCookie(bCookie);
}
}
} [/code]