经验demoiOS DeveloperiOS开发

使用NSURLProtocol实现本地静态文件的web服务器

2017-03-13  本文已影响604人  爱自由鹏
需求前提:

最近公司有这样一个需求,要用webView加载网页游戏,由于苹果方面不支持webView通过url从服务器端加载游戏,于是html,js等资源文件就放到了本地项目里面,通过webView加载html来实现交互。
但是html/js文件里有指向http/https的请求,这样webView就加载不出来本地资源了,因此我们需要拦截http网络请求,把这些url拦截到,然后构建成我们可以响应的方式。


拦截准备:
假设我们本地服务器的端口为1000,服务器名为:localhost,协议是http
那么需要拦截的URL为:http://localhost:1000


实现思路:
拦截URL有如下两种方式:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;

尝试拦截 https://www.baidu.com, 此代理方法确实拦截到了这个url,但是拦截不到内部图片等具体资源的url,因此猜想1失效。

webView拦截URL.png

尝试拦截 https://www.baidu.com, 此代理方法拦截到了所有资源的url,因此猜想2可行。

NSURLProtocol拦截URL.png

实现流程:
一、在想要拦截的地方先注册:

[NSURLProtocol registerClass:[CustomURLProtocol class]];

不想拦截则取消注册:

[NSURLProtocol unregisterClass:[CustomURLProtocol class]];

二、拦截网络请求,NSURLProtocol会依次执行下列方法:
1.该方法会拿到request的对象,我们可以通过该方法的返回值来筛选request是否需要被NSURLProtocol做拦截处理。

+ (BOOL)canInitWithRequest:(NSURLRequest *)request
{
    NSString *monitorStr = request.URL.absoluteString;
//    NSLog(@"monitorStr=%@",monitorStr);
    
    // 只处理 http://localhost:1000/... 的请求
    if ( ([request.URL.absoluteString hasPrefix:@"http://localhost:1000”]))
    {
        //看看是否已经处理过了,防止无限循环
        if ([NSURLProtocol propertyForKey:URLProtocolHandledKey inRequest:request]) {
            return NO;
        }
        
        return YES;
    }
    return NO;
}
NSURLProtocol拦截资源地址.png

2.在该方法中,我们可以对request进行处理。例如修改请求头部信息等。最后返回一个处理后的request实例。例如我们拦截到 https://www.baidu.com, 而通过修改request,将url指向http://www.jianshu.com。 类似于webView代理方法拦截,将其指向一个新的url。如果不修改,则返回request本身。

+ (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
//    NSMutableURLRequest *mutableReqeust = [request mutableCopy];
//    mutableReqeust = [self redirectHostInRequset:mutableReqeust];
    return request;
}

3.在该方法中,把(处理过的或者不需处理的)request重新发送出去。我们要做的就是修改响应体response,骗过服务器,按我们拼接响应的方式去响应。以下为拼接响应体代码。

- (void)startLoading
{
    //1.获取资源文件路径 ajkyq/index.html
    NSURL *url = [self request].URL;
    NSString *resourcePath = url.path;
    resourcePath = [resourcePath substringFromIndex:1];//把第一个/去掉
    
    //2.读取资源文件内容
    NSString *path = [[NSBundle mainBundle] pathForResource:resourcePath ofType:nil];
    NSFileHandle *file = [NSFileHandle fileHandleForReadingAtPath:path];
    NSData *data = [file readDataToEndOfFile];
    [file closeFile];
    
    //3.拼接响应Response
    NSInteger dataLength = data.length;
    NSString *mimeType = [self getMIMETypeWithCAPIAtFilePath:path];
    NSString *httpVersion = @"HTTP/1.1";
    NSHTTPURLResponse *response = nil;
    
    if (dataLength > 0) {
        response = [self jointResponseWithData:data dataLength:dataLength mimeType:mimeType requestUrl:url statusCode:200 httpVersion:httpVersion];
    } else {
        response = [self jointResponseWithData:[@"404" dataUsingEncoding:NSUTF8StringEncoding] dataLength:3 mimeType:mimeType requestUrl:url statusCode:404 httpVersion:httpVersion];
    }
    
    //4.响应
    [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
    [[self client] URLProtocol:self didLoadData:data];
    [[self client] URLProtocolDidFinishLoading:self];
}
 
#pragma mark - 拼接响应Response
-(NSHTTPURLResponse *)jointResponseWithData:(NSData *)data dataLength:(NSInteger)dataLength mimeType:(NSString *)mimeType requestUrl:(NSURL *)requestUrl statusCode:(NSInteger)statusCode httpVersion:(NSString *)httpVersion
{
    NSDictionary *dict = @{@"Content-type":mimeType,
                           @"Content-length":[NSString stringWithFormat:@"%ld",dataLength]};
    NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:requestUrl statusCode:statusCode HTTPVersion:httpVersion headerFields:dict];
    return response;
}

备注:以上为NSURLProtocol实现拦截URL的流程,目前只适用于UIWebView,至于WKWebView拦截URL的实现方式后续会补充(苹果做了一些操作,导致用不能用以上方式拦截WKWebView的URL)。我列举了几篇文章,思路是相通的。我会尽快把我写的demo上传到github,和大家分享。

1.http://www.jianshu.com/p/02781c0bbca9 NSURLProtocol全攻略
2.https://github.com/liujinlongxa/NSURLProtocolDemo/blob/master/NSURLProtocolDemo/MySessionURLProtocol.m NSURLProtocolDemo
3.https://github.com/rnapier/RNCachingURLProtocol/blob/master/RNCachingURLProtocol.m 基于缓存的NSURLProtocol
4.https://github.com/yeatse/NSURLProtocol-WebKitSupport 基于WKWebKit的NSURLProtocol拦截
5.http://www.cnblogs.com/goodboy-heyang/p/5193741.html iOS开发之网络编程--获取文件的MIMEType

上一篇下一篇

猜你喜欢

热点阅读