iOS__监听webView的网络请求,并获取网络请求回来的数据

回复 星标
更多

iOS__监听webView的网络请求,并获取网络请求回来的数据

导语:

最近,webAPP比较火,公司也在用JS框架开发移动APP,web前端的同事负责用JS开发内容,负责iOS的我 和 负责Android的同事,就简单的搭建一个架子.

但是,我在开发中就遇到一些问题,比如本篇文章要讲的webView获取网络请求返回的Session,开始我也是一头雾水,经过一番折腾,到百度,Google.还是找到了解决的办法.

第一步:创建一个继承NSURLProtocol的类

在.m文件中声明NSURLConnection的属性,而且遵守NSURLConnectionDelegate,代码如下:

#import "CustomURLProtocol.h"

static NSString * const URLProtocolHandledKey =   @"URLProtocolHandledKey";      
@interface CustomURLProtocol ()<NSURLConnectionDelegate>
@property (nonatomic, strong) NSURLConnection *connection
@end
  • NSURLConnection: 提供支持执行异步加载URL请求,向数据库提供数据客户提供的代理(英语不好,找Google翻译的)

第二步: 去重写NSURLProtocol的方法

代码如下:

//This method determines whether this protocol can handle the given request.
+ (BOOL)canInitWithRequest:(NSURLRequest *)request
{
    //只处理http和https请求
    NSString *scheme = [[request URL] scheme];
    if ( ([scheme caseInsensitiveCompare:@"http"] == NSOrderedSame ||
    [scheme caseInsensitiveCompare:@"https"] == NSOrderedSame)) {
    //看看是否已经处理过了,防止无限循环
    if ([NSURLProtocol propertyForKey:URLProtocolHandledKey inRequest:request]) {
        return NO;
    }
    Log(@"relativePath -- %@",request.URL.relativePath);
    // 可以做一些网络请求的需要的事情(如:带cookie等等)
    return YES;
}

//This method returns a canonical version of the given request.
+ (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
  return request;
}

//Compares two requests for equivalence with regard to caching.
+ (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a toRequest:(NSURLRequest *)b
{
   return [super requestIsCacheEquivalent:a toRequest:b];
}

//Starts protocol-specific loading of a request.
- (void)startLoading
{
  NSMutableURLRequest *mutableReqeust = [[self request] mutableCopy];
  //打标签,防止无限循环
  [NSURLProtocol setProperty:@YES forKey:URLProtocolHandledKey inRequest:mutableReqeust];
  self.connection = [NSURLConnection connectionWithRequest:mutableReqeust delegate:self];
}

//tops protocol-specific loading of a request. 
- (void)stopLoading
{
  [self.connection cancel];
}

第三步: 实现NSURLConnectionDelegate

的方法代码如下:

#pragma mark - NSURLConnectionDelegate
/// 网络请求返回数据
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
  NSHTTPURLResponse *httpresponse = (NSHTTPURLResponse *)response;
  if([httpresponse respondsToSelector:@selector(allHeaderFields)]){
    NSDictionary *di  = [httpresponse allHeaderFields];
    NSArray *keys = [di allKeys];
    for(int i=0; i<di.count;i++){
        NSString *key = [keys objectAtIndex:i];
        NSString *value=[di objectForKey:key];
        if([key rangeOfString:@"Set-Cookie"].location != NSNotFound)
        {
            Log(@"response_header_value -- %@",value);
            // 获取Session
        }
    }
}

  [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
}

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
  [self.client URLProtocol:self didLoadData:data];
}

- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
  [self.client URLProtocolDidFinishLoading:self];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
  [self.client URLProtocol:self didFailWithError:error];
}

第四步:在AppDelegate.m中注册

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  //注册protocol
  [NSURLProtocol registerClass:[CustomURLProtocol class]];
  return YES;
}

结语:

也是第一次了解这方面的知识,对你有帮助就帮忙点个赞,有错误的地方望大家指出来,谢谢😁😁

新窗口打开 关闭