在Android上使用BasicHttpRequest从webview共享cookie

作为http get的一部分,我无法发送cookie。 首先我要去一个webview中的一个login页面给我一个cookie。 我已经检查并将cookie存储在CookieManager中。 然后,我使用BasicHttpRequest从同一个域中获取特定的URL。 我期望从login中得到的cookie附加到我的头文件中,但在Wireshark中查看它不在那里。 我search了很多类似的问题,并确保:

  • 我正在使用CookieSyncManager,所以我希望会话中的cookie可以保留。 我不认为这是一个CookieSyncManagerasynchronous的问题,因为我保持每5秒击中一次URL并且从不添加cookie。
  • 我怀疑我需要告诉我的http请求关于我的cookie存储,但我googlesearch的解决scheme不为我编译。 它看起来像我想做的东西看起来像context.setAttribute(ClientContext.COOKIE_STORE,this.cookieStore),但我不知道如何从CookieManager获取默认CookieStore。 一些代码似乎调用cookieManager.getCookieStore(),但不能在Android上为我编译。 看着文档,我看不到一种方式来得到似乎疯狂的CookieStore – 我错过了明显的东西?

我在我的webview中启动login页面的代码如下所示:

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); 

然后我的代码来检查cookie是否有如下所示:

 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请求我做

 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; } 

感谢您阅读这个! 任何build议感激地收到,

艾米

Solutions Collecting From Web of "在Android上使用BasicHttpRequest从webview共享cookie"

连接cookies终于为我工作! 我可能没有做到这一点最简单的方法,但至less是有效的。 我的重大突破是下载和附加android源代码,以便我可以一步一步看看发生了什么。 这里有说明http://blog.michael-forster.de/2008/12/view-android-source-code-in-eclipse.html – 向下滚动并阅读来自Volure的最简单下载的评论。 如果您是在Android上开发,我强烈build议您这样做。

现在到工作的cookie代码 – 大部分的变化是在我的网页实际得到的代码 – 我必须build立一个COOKIE_STORE和一个COOKIESPEC_REGISTRY。 然后,我也必须改变我的连接types,因为cookie代码将其转换为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; } 

我设置我的cookie的代码和getMeAWebpage()看起来像:

 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)