android - 在 Android 上使用 BasicHttpRequest 从 webview 共享 cookie

标签 android cookies httprequest android-webview

我在发送 cookie 作为 http get 的一部分时遇到问题。首先,我转到 web View 中的登录页面,它给了我一个 cookie。我检查过,cookie 存储在 CookieManager 中。然后我使用 BasicHttpRequest 从同一域获取特定 URL。我希望我从登录获得的 cookie 附加到我的标题以获取,但在 Wireshark 中查看它不存在。我用谷歌搜索并阅读了很多类似的问题,并确保:

  • 我正在使用 CookieSyncManager,所以我希望 session 中的 cookie 能够持续存在。我不认为 CookieSyncManager 是异步的有什么问题,因为我每 5 秒就访问一次 URL,并且从未添加过 cookie。
  • 我怀疑我需要告诉我的 cookie 存储的 http 请求,但我在 google 上搜索的解决方案并没有为我编译。看起来我想做一些看起来像 context.setAttribute(ClientContext.COOKIE_STORE, this.cookieStore) 的事情,但我不知道如何从 CookieManager 获取默认的 CookieStore。一些代码似乎调用了 cookieManager.getCookieStore() 但它不能在 Android 上为我编译。查看文档,我看不到获取 CookieStore 的方法,这看起来很疯狂——我是否遗漏了一些明显的东西?

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

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

感谢您阅读到这里!非常感谢收到任何建议,

艾米

最佳答案

附加 cookie 终于对我有用了!我可能没有以最简单的方式完成它,但至少它有效。我的重大突破是下载并附加 android 源代码,这样我就可以逐步查看发生了什么。这里有说明http://blog.michael-forster.de/2008/12/view-android-source-code-in-eclipse.html - 向下滚动并阅读 Volure 的评论以获得最简单的下载。如果您在 Android 上进行开发,我强烈建议您这样做。

现在开始使用 cookie 代码 - 大多数更改都在实际获取我的网页的代码中 - 我必须设置 COOKIE_STORE 和 COOKIESPEC_REGISTRY。然后我还必须更改我的连接类型,因为 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)

关于android - 在 Android 上使用 BasicHttpRequest 从 webview 共享 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8080761/

相关文章:

php - 在点击时设置 PHP cookie

ruby-on-rails-3 - 使用 iframe 时,Safari 中的 ActionController::InvalidAuthenticityToken 异常

node.js - 从响应对象获取请求体

Java/安卓 : Reading/writing a byte array over a socket

java - java上http post方法、HttpServletResponse和cookie的问题

android - 我可以使用 Intent 调用相机吗?

java httprequest 从请求中获取正文

c++ - 如何从QT中的http请求中删除授权 header

java - Android:无效使用 SingleClientConnManager:连接仍然分配

android - fragment 生命周期 Android