WebViewJavascriptBridge传递Header、Cookie

一、简述:

WebViewJavascriptBridge库:底层还是通过协议拦截的方式来进行交互,但是对H5与Native的交互做了比较好的封装,使得H5与Native的相互调用变得相对简单,最主要是该库在iOS和Android上都有实现版本,统一了交互方式。
交互流程:
这里写图片描述

二、传递Cookie:

1、Android
 /**
 * 同步cookie
 */
  public static void synCookies(Context context, String url, String cookie) {
    CookieSyncManager.createInstance(context);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setAcceptCookie(true);
    //set之前清除所有cookie
    cookieManager.removeAllCookie();
    cookieManager.setCookie(url, "auth="+cookie);// cookies是在HttpClient中获得的cookie
    CookieSyncManager.getInstance().sync();
  }  
2、iOS:
    NSDictionary *properties = [[NSMutableDictionary alloc] init]
    [properties setValue:@"keyvalue" forKey:@"JSESSIONID"]; 
    [request setValue:properties forHTTPHeaderField:@"Cookie"];  

三、传递Header:

1、Android

需要在类库的BridgeWebViewClient类中,修改loadUrl方法

    Map<String,String> extraHeaders = new HashMap<String, String>();
    extraHeaders.put("imei", "设备ID");
    //加载网页 添加请求头
    webView.loadUrl(webviewUrl, extraHeaders);

这里写图片描述

2、IOS

需要定义一个可变URLRequest对象,复制request的深拷贝,set Header值后,作为loadRequest参数重新加载请求
Link:http://stackoverflow.com/questions/25539837/how-to-add-customize-http-headers-in-uiwebview-request-my-uiwebview-is-based-on

  //(NSURLRequest*)request //前提获取NSURLRequest对象
  NSMutableURLRequest *re = [[NSMutableURLRequest alloc] init];//alloc init      not required
  re = (NSMutableURLRequest *) request.mutableCopy;
  [re setValue:@"Your Custom Value" forHTTPHeaderField:@"Yout Custom     Header"];
  [webView loadRequest:re] ;

四、Java解析Cookie和Header

1、Cookie:
 request.getCookies();
2、Header:
  Enumeration headerNames = request.getHeaderNames();
  while (headerNames.hasMoreElements()) {
       String key = (String) headerNames.nextElement();
       String value = request.getHeader(key);
       map.put(key, value);
  }
  request.getHeader("auth") 

参考资料:http://blog.csdn.net/t12x3456/article/details/17385263
http://stackoverflow.com/questions/478387/change-user-agent-in-uiwebview-iphone-sdk/23654363#23654363

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值