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

0 0
原创粉丝点击