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

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

艾米

解决方法

附加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)

在Android上通过BasicHttpRequest从webview共享cookies的更多相关文章

  1. html5利用canvas实现颜色容差抠图功能

    这篇文章主要介绍了html5利用canvas实现颜色容差抠图功能,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下

  2. 详解如何通过H5(浏览器/WebView/其他)唤起本地app

    这篇文章主要介绍了详解如何通过H5(浏览器/WebView/其他)唤起本地app的相关资料,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  3. Canvas图片分割效果的实现

    这篇文章主要介绍了Canvas图片分割效果的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

  4. HTML5 Canvas实现放大镜效果示例

    这篇文章主要介绍了HTML5 Canvas实现放大镜效果示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

  5. Html5 Canvas实现图片标记、缩放、移动和保存历史状态功能 (附转换公式)

    这篇文章主要介绍了Html5 Canvas实现图片标记、缩放、移动和保存历史状态功能 (附转换公式),本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  6. html5如何在Canvas中实现自定义路径动画示例

    本篇文章主要介绍了html5如何在Canvas中实现自定义路径动画示例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  7. canvas实现圆形进度条动画的示例代码

    这篇文章主要介绍了canvas实现圆形进度条动画的相关资料,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  8. HTML5 Web缓存和运用程序缓存(cookie,session)

    这篇文章主要介绍了HTML5 Web缓存和运用程序缓存(cookie,session),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  9. html5 移动端视频video的android兼容(去除播放控件、全屏)

    这篇文章主要介绍了html5 移动端视频video的android兼容,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

  10. HTML5 WebSocket实现点对点聊天的示例代码

    这篇文章主要介绍了HTML5 WebSocket实现点对点聊天的示例代码的相关资料,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

随机推荐

  1. bluetooth-lowenergy – Altbeacon库无法在Android 5.0上运行

    昨天我在Nexus4上获得了Android5.0的更新,并且altbeacon库停止了检测信标.似乎在监视和测距时,didEnterRegion和didRangeBeaconsInRegion都没有被调用.即使RadiusNetworks的Locate应用程序现在表现不同,一旦检测到信标的值,它们就不再得到更新,并且通常看起来好像信标超出了范围.我注意到的一点是,现在在logcat中出现以下行“B

  2. android – react-native动态更改响应者

    我正在使用react-native进行Android开发.我有一个视图,如果用户长按,我想显示一个可以拖动的动画视图.我可以使用PanResponder实现这一点,它工作正常.但我想要做的是当用户长按时,用户应该能够继续相同的触摸/按下并拖动新显示的Animated.View.如果您熟悉Google云端硬盘应用,则它具有类似的功能.当用户长按列表中的任何项目时,它会显示可拖动的项目.用户可以直接拖

  3. android – 是否有可能通过使用与最初使用的证书不同的证书对其进行签名来发布更新的应用程序

    是否可以通过使用与最初使用的证书不同的证书进行签名来发布Android应用程序的更新?我知道当我们尝试将这样的构建上传到市场时,它通常会给出错误消息.但有没有任何出路,比如将其标记为主要版本,指定市场中的某个地方?解决方法不,你不能这样做.证书是一种工具,可确保您是首次上传应用程序的人.所以总是备份密钥库!

  4. 如何检测Android中是否存在麦克风?

    ..所以我想在让用户访问语音输入功能之前检测麦克风是否存在.如何检测设备上是否有麦克风.谢谢.解决方法AndroidAPI参考:hasSystemFeature

  5. Android – 调用GONE然后VISIBLE使视图显示在错误的位置

    我有两个视图,A和B,视图A在视图B上方.当我以编程方式将视图A设置为GONE时,它将消失,并且它正下方的视图将转到视图A的位置.但是,当我再次将相同的视图设置为VISIBLE时,它会在视图B上显示.我不希望这样.我希望视图B回到原来的位置,这是我认为会发生的事情.我怎样才能做到这一点?编辑–代码}这里是XML:解决方法您可以尝试将两个视图放在RelativeLayout中并相对于彼此设置它们的位置.

  6. android – 获得一首歌的流派

    我如何阅读与歌曲相关的流派?我可以读这首歌,但是如何抓住这首歌的流派,它存放在哪里?解决方法检查此代码:

  7. android – 使用textShadow折叠工具栏

    我有一个折叠工具栏的问题,在展开状态我想在文本下面有一个模糊的阴影,我使用这段代码:用:我可以更改textColor,它可以工作,但阴影不起作用.我为阴影尝试了很多不同的值.是否可以为折叠文本投射阴影?

  8. android – 重用arm共享库

    我已经建立了armarm共享库.我有兴趣重用一个函数.我想调用该函数并获得返回值.有可能做这样的事吗?我没有任何头文件.我试过这个Android.mk,我把libtest.so放在/jni和/libs/armeabi,/lib/armeabi中.此时我的cpp文件编译,但现在是什么?我从objdump知道它的名字编辑:我试图用这个android.mk从hello-jni示例中添加prebuild库:它工作,但libtest.so相同的代码显示以下错误(启动时)libtest.so存在于libhello-j

  9. android – 为NumberPicker捕获键盘’Done’

    我有一个AlertDialog只有一些文本,一个NumberPicker,一个OK和一个取消.(我知道,这个对话框还没有做它应该保留暂停和恢复状态的事情.)我想在软键盘或其他IME上执行“完成”操作来关闭对话框,就像按下了“OK”一样,因为只有一个小部件可以编辑.看起来处理IME“Done”的最佳方法通常是在TextView上使用setonEditorActionListener.但我没有任何Te

  10. android – 想要在调用WebChromeClient#onCreateWindow时知道目标URL

    当我点击一个带有target=“_blank”属性的超链接时,会调用WebChromeClient#onCreateWindow,但我找不到新的窗口将打开的新方法?主页url是我唯一能知道的东西?我想根据目标网址更改应用行为.任何帮助表示赞赏,谢谢!

返回
顶部