在Android上通过BasicHttpRequest从webview共享cookies

前端之家收集整理的这篇文章主要介绍了在Android上通过BasicHttpRequest从webview共享cookies前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
发送cookies作为http get的一部分遇到麻烦.首先我去一个webview中的一个登录页面给我一个cookie.我已经检查并将cookie存储在CookieManager中.然后我使用BasicHttpRequest从同一个域获取一个特定的URL.我希望我从登录中获得的cookie被附加到我的头文件中,但是在Wireshark中看到它不在那里.我已经搜索并阅读了很多类似的问题,并确定:

>我正在使用CookieSyncManager,所以我希望我的cookies从会话将持续.我不认为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,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;
}

谢谢你读这个远!有意见的建议,

艾米

@R_404_323@

附加cookies终于为我工作了!我可能没有做到最简单的方法,但至少它是有效的.我的大突破是下载和附加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,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",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,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",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)

原文链接:https://www.f2er.com/android/312272.html

猜你在找的Android相关文章