参与分享的WebView饼干在Android BasicHtt prequest [英] Sharing cookies from webview with BasicHttpRequest on Android
问题描述
我无法发送的cookie作为一个HTTP GET的一部分。首先,我去一个登录页面的WebView这给了我一个cookie中。我已经检查和cookie被存储在CookieManager。然后,我用一个BasicHtt prequest得到来自同一个域特定URL。我希望,我从登录了cookie被贴在我的头的GET,但看着它在Wireshark中它不存在。我GOOGLE和读了很多类似的问题,并取得了肯定:
I'm having trouble sending cookies as part of an http get. First I go to a login page within a webview which gives me a cookie. I have checked and the cookie is being stored in the CookieManager. Then I use a BasicHttpRequest to get a particular URL from the same domain. I would expect the cookie that I got from the login to be attached to my headers for the get, but looking at it in Wireshark it's not there. I've googled and read a lot of similar questions and have made sure that:
- 在我使用的CookieSyncManager所以我希望我的Cookie会话将持续。我不认为它与CookieSyncManager是异步的,因为我不停的网址每隔5秒,饼干永远不会加入一个问题。
- 我怀疑我要告诉我的关于我的cookie存储的http请求,但我GOOGLE的解决方案不编译我。它看起来像我想要做的事情看起来像context.setAttribute(ClientContext.COOKIE_STORE,this.cookieStore),但我无法弄清楚如何从CookieManager得到默认的CookieStore。有些code似乎调用cookieManager.getCookieStore(),但是,这并不编译我在Android上。在看文档,我不能看到一个办法让这似乎疯了CookieStore的 - 我失去了一些东西明显?
我的code启动登录页面在我的WebView的样子:
My code to start up the login page in my webview looks like:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// use cookies to remember a logged in status
CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().startSync();
//not sure if I need to do this
CookieManager cookie_manager = CookieManager.getInstance();
cookie_manager.setAcceptCookie(true);
webview = new WebView(this);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new HelloWebViewClient()); // if user clicks on a url we need to steal that click, also steal the back button
webview.loadUrl("http://"+my_server+"/api/v1/login");
setContentView(webview);
然后我的code检查cookie的存在是这样的:
Then my code to check the cookie is there looks like:
public static boolean CheckAuthorised() {
CookieSyncManager.getInstance().sync();
CookieManager cookie_manager = CookieManager.getInstance();
String cookie_string = cookie_manager.getCookie("http://"+my_server+"/api/v1/login");
System.out.println("lbp.me cookie_string: " + cookie_string);
if(cookie_string != null)
{
String[] cookies = cookie_string.split(";");
for (String cookie : cookies)
{
if(cookie.matches("API_AUTH=.*"))
{
// maybe we need to store the cookie for the root of the domain?
cookie_manager.setCookie("http://"+my_server, cookie_string);
// maybe we need to store the cookie for the url we're actually going to access?
cookie_manager.setCookie("http://"+my_server+"/api/v1/activity", cookie_string);
CookieSyncManager.getInstance().sync();
return true;
}
}
}
return false;
}
和实际上使我的http请求
And to actually make the http request I do
public static HttpResponse getMeAWebpage(String host_string, int port, String url)
throws Exception {
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
HttpProtocolParams.setUseExpectContinue(params, true);
BasicHttpProcessor httpproc = new BasicHttpProcessor();
// Required protocol interceptors
httpproc.addInterceptor(new RequestContent());
httpproc.addInterceptor(new RequestTargetHost());
// Recommended protocol interceptors
httpproc.addInterceptor(new RequestConnControl());
httpproc.addInterceptor(new RequestUserAgent());
httpproc.addInterceptor(new RequestExpectContinue());
HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
HttpContext context = new BasicHttpContext(null);
// HttpHost host = new HttpHost("www.svd.se", 80);
HttpHost host = new HttpHost(host_string, port);
DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
//CookieManager cookie_manager = CookieManager.getInstance();
//CookieStore cookie_store = cookie_manager.getCookieStore(); //The method getCookieStore() is undefined for the type CookieManager
//context.setAttribute(ClientContext.COOKIE_STORE, cookie_store);
HttpResponse response = null;
try {
if (!conn.isOpen()) {
Socket socket = new Socket(host.getHostName(), host.getPort());
conn.bind(socket, params);
}
BasicHttpRequest request = new BasicHttpRequest("GET", url);
System.out.println(">> Request URI: "
+ request.getRequestLine().getUri());
System.out.println(">> Request: "
+ request.getRequestLine());
request.setParams(params);
httpexecutor.preProcess(request, httpproc, context);
response = httpexecutor.execute(request, conn, context);
response.setParams(params);
httpexecutor.postProcess(response, httpproc, context);
String ret = EntityUtils.toString(response.getEntity());
System.out.println("<< Response: " + response.getStatusLine());
System.out.println(ret);
System.out.println("==============");
if (!connStrategy.keepAlive(response, context)) {
conn.close();
} else {
System.out.println("Connection kept alive...");
}
} catch(UnknownHostException e) {
System.out.println("UnknownHostException");
} catch (HttpException e) {
System.out.println("HttpException");
} finally {
conn.close();
}
return response;
}
感谢您对远阅读!感激地收到任何建议,
Thank you for reading this far! Any suggestions gratefully received,
艾米
推荐答案
附加饼干终于为我工作!我可能不会做它最简单的方法,但至少它的工作原理。我的大突破是下载和安装android的来源,这样我就可以逐步完成,看看发生了什么事。有说明这里 HTTP: //blog.michael-forster.de/2008/12/view-android-source-$c$c-in-eclipse.html - 向下滚动,阅读Volure的注释简单的下载。我强烈强烈建议这样做,如果你正在开发在Android上。
Attaching cookies is finally working for me! I might not have done it the easiest way, but at least it works. My big breakthrough was downloading and attaching the android sources, so that I could step through and see what was happening. There are instructions here http://blog.michael-forster.de/2008/12/view-android-source-code-in-eclipse.html - scroll down and read the comment from Volure for the simplest download. I highly highly recommend doing this if you're developing on Android.
现在到工作的cookies code - 大部分的变化是在code,其实让我我的网页 - 我必须建立一个COOKIE_STORE和COOKIESPEC_REGISTRY。然后,我也不得不改变我的连接类型,因为饼干code的铸造到一个ManagedClientConnection:
Now on to the working cookies code - most changes were in the code that actually gets me my webpage - I had to set up a COOKIE_STORE and a COOKIESPEC_REGISTRY. Then I also had to change my connection type because the cookies code was casting it to a ManagedClientConnection:
public static HttpResponse getMeAWebpage(String host_string, int port, String url)
throws Exception {
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
HttpProtocolParams.setUseExpectContinue(params, true);
//params.setParameter("cookie", cookie);
BasicHttpProcessor httpproc = new BasicHttpProcessor();
// Required protocol interceptors
httpproc.addInterceptor(new RequestContent());
httpproc.addInterceptor(new RequestTargetHost());
// Recommended protocol interceptors
httpproc.addInterceptor(new RequestConnControl());
httpproc.addInterceptor(new RequestUserAgent());
httpproc.addInterceptor(new RequestExpectContinue());
httpproc.addInterceptor(new RequestAddCookies());
HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
HttpContext context = new BasicHttpContext(null);
// HttpHost host = new HttpHost("www.svd.se", 80);
HttpHost host = new HttpHost(host_string, port);
HttpRoute route = new HttpRoute(host, null, false);
// Create and initialize scheme registry
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
SingleClientConnManager conn_mgr = new SingleClientConnManager(params, schemeRegistry);
ManagedClientConnection conn = conn_mgr.getConnection(route, null /*state*/);
ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
CookieStore cookie_store = new BasicCookieStore();
cookie_store.addCookie(cookie);
context.setAttribute(ClientContext.COOKIE_STORE, cookie_store);
// not sure if I need to add all these specs, but may as well
CookieSpecRegistry cookie_spec_registry = new CookieSpecRegistry();
cookie_spec_registry.register(
CookiePolicy.BEST_MATCH,
new BestMatchSpecFactory());
cookie_spec_registry.register(
CookiePolicy.BROWSER_COMPATIBILITY,
new BrowserCompatSpecFactory());
cookie_spec_registry.register(
CookiePolicy.NETSCAPE,
new NetscapeDraftSpecFactory());
cookie_spec_registry.register(
CookiePolicy.RFC_2109,
new RFC2109SpecFactory());
cookie_spec_registry.register(
CookiePolicy.RFC_2965,
new RFC2965SpecFactory());
//cookie_spec_registry.register(
// CookiePolicy.IGNORE_COOKIES,
// new IgnoreSpecFactory());
context.setAttribute(ClientContext.COOKIESPEC_REGISTRY, cookie_spec_registry);
HttpResponse response = null;
try {
if (!conn.isOpen()) {
conn.open(route, context, params);
}
BasicHttpRequest request = new BasicHttpRequest("GET", url);
System.out.println(">> Request URI: "
+ request.getRequestLine().getUri());
System.out.println(">> Request: "
+ request.getRequestLine());
request.setParams(params);
httpexecutor.preProcess(request, httpproc, context);
response = httpexecutor.execute(request, conn, context);
response.setParams(params);
httpexecutor.postProcess(response, httpproc, context);
String ret = EntityUtils.toString(response.getEntity());
System.out.println("<< Response: " + response.getStatusLine());
System.out.println(ret);
System.out.println("==============");
if (!connStrategy.keepAlive(response, context)) {
conn.close();
} else {
System.out.println("Connection kept alive...");
}
} catch(UnknownHostException e) {
System.out.println("UnknownHostException");
} catch (HttpException e) {
System.out.println("HttpException");
} finally {
conn.close();
}
return response;
}
我的code设置我的cookie生活在同一个类getMeAWebpage()是这样的:
My code to set up my cookie lives in the same class as getMeAWebpage() looks like:
public static void SetCookie(String auth_cookie, String domain)
{
String[] cookie_bits = auth_cookie.split("=");
cookie = new BasicClientCookie(cookie_bits[0], cookie_bits[1]);
cookie.setDomain(domain); // domain must not have 'http://' on the front
cookie.setComment("put a comment here if you like describing your cookie");
//cookie.setPath("/blah"); I don't need to set the path - I want the cookie to apply to everything in my domain
//cookie.setVersion(1); I don't set the version so that I get less strict checking for cookie matches and am more likely to actually get the cookie into the header! Might want to play with this when you've got it working...
}
我真的希望这会有所帮助,如果你有类似的问题 - 我觉得我一直在敲打我的头靠在墙上的一两个星期!现在对于一个当之无愧的庆祝杯茶:O)
I really hope this helps if you're having similar problems - I feel like I've been banging my head against a wall for a couple of weeks! Now for a well-deserved celebratory cup of tea :o)
这篇关于参与分享的WebView饼干在Android BasicHtt prequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!