UIWebView加载时添加请求头
来源:互联网 发布:凶宅数据库 编辑:程序博客网 时间:2024/05/17 04:47
http://codecloud.net/16258.html
http://stackoverflow.com/questions/25539837/how-to-add-customize-http-headers-in-uiwebview-request-my-uiwebview-is-based-on
想要在请求头加参其实很简单,只要通过以下代码:
[request addValue:"head" forHTTPHeaderField:@"key"];
现在主要问题是要在每次加载都在请求头加参,于是我在网上搜到这篇文章 UIWebView 设置请求头,基本上可以解决我的需求。下面分析以下代码:
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//先判断是否含有请求头,打破死循环
let dic:Dictionary<String,AnyObject> = request.allHTTPHeaderFields!
let token = dic["UserToken"]
if (token != nil) {
return true
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let newUrl = request.URL
let newRequest:NSMutableURLRequest = NSMutableURLRequest.init(URL: newUrl!)
newRequest.addValue(LoginInfoModel.sharedInstance.m_auth, forHTTPHeaderField: "UserToken")
self.webView.loadRequest(newRequest)
})
}
return false
}
如上,在uiwebview的代理方法webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) 中拦截网络请求,先检验请求中是否含有参数,有参数即直接通过(这一步十分关键,因为拦截的请求如没有参数,会先在请求头添加参数,再让web view重新loadRequest,并且在代理方法中要返回NO,loadRequest会重新走这个代理方法,如果没有以上检测通过return YES的话,就会陷入死循环,)。另外,之所以要在主线程中操作,我觉得是与webview的底层加载有关,webview加载时应该是开了子线程,所以重新加载要在主线程操作,保证线程安全。至于文章中提及这种做法进入有iFrame的的页面会有bug,由于我们后台页面没有iFrame,因此忽略掉。
另外还搜到另一种做法 NSURLProtocol学习笔记-UIWebView 设置请求头,这种做法听说更加完美地避免bug,我需要再验证下,后续再更新……
结束
Sometimes Cookies are not set even after you assign all http headers. it is better to create mutable request and copy your nsurlrequest and add your custom header to it so that all information from original request is retained in mutable one.
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType{ if(check if key not present){ 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] ; return NO; }return YES;}
- UIWebView加载时添加请求头
- iOS - UIWebView 加载重定向url、添加请求头信息
- iOS如何添加自定义UIWebView的HTTP请求头
- iOS UIWebview添加请求头的两种方式
- Picasso加载图片添加请求头addHeader
- UIWebview加载post请求
- UIWebView加载POST请求
- iOS UIWebView 自定义请求头 UserAgent
- UIWebView加载POST请求 加载html
- AFN 添加请求头
- webview添加请求头
- AFNetworking 添加请求头
- HTTPS请求添加请求头
- 给UIWebView添加自定义头视图
- iOS7 UIWebView设置支持加载HTTPS请求
- AFnetworking post 添加请求头
- 请求头添加UTF8编码
- 关于curl添加请求头
- Ubuntu x64安装Android studio 全部步骤和问题解决
- clipChildren属性使用说明
- 解决 侵入式下 EditText位于屏幕底部时会被软键盘覆盖的问题
- 谷歌手机模拟浏览器
- 谁动了你的数据?——再不用担心
- UIWebView加载时添加请求头
- c#移动无边框form窗口
- nsis安装包_示例脚本语法解析
- Java 静态方法和实例方法的区别
- Domino SSL SHA2启用手册
- 欢迎使用CSDN-markdown编辑器
- OkHttp3使用详解
- android性能优化
- UITableView编辑模式