zoukankan      html  css  js  c++  java
  • ReactNative 当前url和cookies的获取

    前面大概介绍了react-native的运行helloword级别的入门,所以之后简单的东西就不写了,毕竟官网上都能够找到。

    reactnative官网:https://facebook.github.io/react-native/docs/getting-started.html

    reactnative中文网:http://reactnative.cn/docs/0.25/getting-started.html

    之后我会把工作中遇到的一些react-native的深坑分享一下。

    正题===========================

    客户端cookies的获取就是一个大坑。

    1.使用三方

    研究ReactNative的源码发现,框架中并没有实现iOS的NSHTTPCookieStorage的api,所以搜遍百度谷歌和bing,最终找到了一个哥们写的第三方cookies工具:

    https://github.com/joeferraro/react-native-cookies

    这里需要一提的是,我需要取得cookie不仅是dictionary形式的cookies,而是用于http请求的cookiesHeader(比较特殊),其格式是string,在OC中取得的方式是:

    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:url];
    NSDictionary *header = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];

    但这一块原作者的框架中貌似存在一定的问题,所以我写了一个pull request,具体可以访问我fork的项目:

    https://github.com/rayshen/react-native-cookies

    (如果你需要取得的Cookie是用来解析取值或是保存重新加入的,用get("url",res)或者getAll()函数取得的比较适合)

    2.获取当前url

    这就需要结合webview控件来进行操作了。

    首先我们需要确定当前的url,当前的url可以从webview控件绑定的事件onNavigationStateChange去取得:

    onNavigationStateChange={this.onNavigationStateChange.bind(this)}

     onNavigationStateChange(navState) {
         console.log(navState.url);
         this.curUrl = navState.url;
      }
    

    3.取得url的cookie header:

     CookieManager.getHeader(this.curUrl, (err, res) => {
          console.log('Got cookies for url: ' + res.Cookie);
     })
    

    4.取得url的所有cookies

    CookieManager.get('http://example.com', (err, res) => {
      console.log(res);
    })
    

      

    5.取得当前所有的cookies

    CookieManager.getAll((err, res) => {
      console.log('cookies!');
      console.log(err);
      console.log(res);
    });
    

    需要注意的是,getAll()和set()都是iOS Only的函数。

     

  • 相关阅读:
    小点
    三.一些常用类
    字符串相关:String,StringBuffer,StringBuilder
    五.二叉树
    四.递归
    三.队列
    二.栈
    一.数组,链表
    RDLC 矩阵图片列表排列顺序乱
    RDLC 矩阵每隔一页就有空白页 矩阵 空白页
  • 原文地址:https://www.cnblogs.com/rayshen/p/5502379.html
Copyright © 2011-2022 走看看