UIWebView加载时添加请求头

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值