NSURLProtocal子類的使用

來源:互聯網
上載者:User

標籤:direct   nsrange   stop   length   case   --   dfa   error:   reserve   

//

//  CustomURLProtocol.m

//  NSURLProtocolExample

//

//  Created by lujb on 15/6/15.

//  Copyright (c) 2015年 lujb. All rights reserved.

//

 

#import "CustomURLProtocol.h"

 

static NSString * const URLProtocolHandledKey = @"URLProtocolHandledKey";

 

@interface CustomURLProtocol ()<NSURLConnectionDelegate>

 

@property (nonatomic, strong) NSURLConnection *connection;

 

@end

 

@implementation CustomURLProtocol

 

+ (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;

        }

        

        return YES;

    }

    return NO;

}

 

+ (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {

    NSMutableURLRequest *mutableReqeust = [request mutableCopy];

    mutableReqeust = [self redirectHostInRequset:mutableReqeust];

    

    

    return [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"]];

}

 

+ (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a toRequest:(NSURLRequest *)b

{

    return [super requestIsCacheEquivalent:a toRequest:b];

}

 

- (void)startLoading

{

    /* 如果想直接返回緩衝的結果,構建一個NSURLResponse對象

    if (cachedResponse) {

        

        NSData *data = cachedResponse.data; //緩衝的資料

        NSString *mimeType = cachedResponse.mimeType;

        NSString *encoding = cachedResponse.encoding;

        

        NSURLResponse *response = [[NSURLResponse alloc] initWithURL:self.request.URL

                                                            MIMEType:mimeType

                                               expectedContentLength:data.length

                                                    textEncodingName:encoding];

        

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

        [self.client URLProtocol:self didLoadData:data];

        [self.client URLProtocolDidFinishLoading:self];

    */

    

    NSMutableURLRequest *mutableReqeust = [[self request] mutableCopy];

    

    //打標籤,防止無限迴圈

    [NSURLProtocol setProperty:@YES forKey:URLProtocolHandledKey inRequest:mutableReqeust];

    

    self.connection = [NSURLConnection connectionWithRequest:mutableReqeust delegate:self];

}

 

- (void)stopLoading

{

    [self.connection cancel];

}

 

#pragma mark - NSURLConnectionDelegate

 

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {

    [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];

}

 

#pragma mark -- private

 

+(NSMutableURLRequest*)redirectHostInRequset:(NSMutableURLRequest*)request

{

    if ([request.URL host].length == 0) {

        return request;

    }

    

    NSString *originUrlString = [request.URL absoluteString];

    NSString *originHostString = [request.URL host];

    NSRange hostRange = [originUrlString rangeOfString:originHostString];

    if (hostRange.location == NSNotFound) {

        return request;

    }

    

    //定向到bing搜尋首頁

    NSString *ip = @"cn.bing.com";

    

    // 替換host

    NSString *urlString = [originUrlString stringByReplacingCharactersInRange:hostRange withString:ip];

    NSURL *url = [NSURL URLWithString:urlString];

    request.URL = url;

 

    return request;

}

@end

 

NSURLProtocal子類的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.