WebViewJavascriptBridge传递Header、Cookie
16lz
2021-01-24
一、简述:
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
更多相关文章
- AndroidStudio使用GreenDao实战
- Android使用AnalogClock和DigitalClock
- Android(安卓)Glide加载图片圆角效果与ImageView的ScaleType冲突
- Android(安卓)Handler
- aFinal框架
- Android(安卓)照相机实现方式
- Android进程中通信的方式
- Android(安卓)Volley完全解析(二),使用Volley加载网络图片
- android 图片加载和缓存开源项目 Picasso