IOS Development-nsurlprotocol

Source: Internet
Author: User

Recently in the project because of the telecommunications over the DNS occurred domain name hijacking, it is necessary to manually redirect the URL request domain name to the specified IP address, but because the request may be through nsurlconnection,nsurlsession or afnetworking, etc., So want to unify to deal with, start is want to pass method swizzling to hook cfnetworking Bottom way, later discovered actually have a better method –nsurlprotocol.

Nsurlprotocol

Nsurlprotocol allows you to redefine the behavior of Apple's URL-loading system (URL Loading systems), and there are many classes in the URL Loading system to handle URL requests, such as Nsurl,nsurlrequest, Nsurlconnection and Nsurlsession, when the URL Loading system uses Nsurlrequest to get the resource, it creates an instance of the Nsurlprotocol subclass, You should not instantiate a nsurlprotocol,nsurlprotocol that looks like a protocol, but it is a class and must use subclasses of that class, and it needs to be registered.

Usage Scenarios

Whether you are through UIWebView, nsurlconnection, or third-party libraries (afnetworking, Mknetworkkit, etc.), they are all based on nsurlconnection or nsurlsession implementations, So you can do a custom operation with Nsurlprotocol.

    • REDIRECT Network requests

    • Ignore network requests, use local cache

    • To customize the return result of a network request

    • Some global network request settings

Intercept Network requests

Subclass Nsurlprotocol and register

@Interface customurlprotocol : nsurlprotocol

@End

The Customurlprotocol is then registered in the Application:didfinishlaunchingwithoptions: method, and once registered, it has the opportunity to process all deliveries to the URL Loading System's network request.

- (BOOL)application:(uiapplication *)application Didfinishlaunchingwithoptions:(nsdictionary *)launchoptions {

//Register Protocol

[nsurlprotocol registerclass:[Customurlprotocol class]];

return YES;

}

Implement Customurlprotocol

Once you're signed up, you can now start implementing some of the Nsurlprotocol methods:

    • +caninitwithrequest:

      This method mainly indicates whether you intend to handle the corresponding request, if you do not intend to process it, return to No,url Loading system will use the default behavior to process, if you intend to process, return Yes, then you need to process the request of all things, This includes fetching the request data and returning it to the URL Loading System. Network data can be easily obtained through nsurlconnection, and each Nsurlprotocol object has a nsurlprotocolclient instance, which can be returned to the URL by the client for the retrieved data Loading System.

      Here's a place to be aware, imagine that when you load a URL resource, the URL Loading system asks Customurlprotocol if it can handle the request, you return yes, and then the URL Loading System creates an Customurlprotocol instance and then calls Nsurlconnection to fetch the data, but this also calls the URL Loading System, and you +caninitwithrequest: Always returns yes so the URL Loading system creates an Customurlprotocol instance that causes an infinite loop. We should ensure that each request is processed only once, by +setproperty:forkey:inrequest: Mark the request that has been processed, and then in +caninitwithrequest: Query whether the request has already been processed, and if yes, return No.

+ (BOOL)caninitwithrequest:(nsurlrequest *)request

{

//Processing HTTP and HTTPS requests only

NSString *scheme = [[request URL] scheme];

if ( [scheme caseinsensitivecompare:@"http"] = = Nsorderedsame | |

[scheme caseinsensitivecompare:@"https"] = = nsorderedsame))

{

//See if it has been processed to prevent infinite loops

if ([nsurlprotocol propertyforkey:urlprotocolhandledkey inrequest: Request]) {

return NO;

}

return YES;

}

return NO;

}

    • +canonicalrequestforrequest:

      Typically, you can simply return the request directly, but you can also modify the request here, such as adding a header, modifying the host, and returning a new request, which is an abstract method that the subclass must implement.

+ (nsurlrequest *) canonicalrequestforrequest:(nsurlrequest *) Request {

nsmutableurlrequest *mutablereqeust = [request mutablecopy];

mutablereqeust = [self redirecthostinrequset:mutablereqeust];

return mutablereqeust;

}

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

}

//Directed to Bing search home

nsstring *IP = @"cn.bing.com";

//Replace domain name

NSString *urlstring = [originurlstring stringbyreplacingcharactersinrange: Hostrange withstring:IP];

nsurl *url = [nsurl urlwithstring:urlstring];

request. URL = url;

return request;

}

    • +requestiscacheequivalent:torequest:

      The main decision is whether the two request is the same, if the same can be used to cache data, usually only need to call the implementation of the parent class.

+ (BOOL)requestiscacheequivalent:(nsurlrequest *)a torequest :(nsurlrequest *)b

{

return [super requestiscacheequivalent:a torequest:b ];

}

    • -startloading-stoploading

      The two methods are primarily to start and cancel the corresponding request, and to indicate which request has already been processed.

- (void)startloading

{

nsmutableurlrequest *mutablereqeust = [[self request] mutablecopy ];

//Mark change request has been processed to prevent an infinite loop

[nsurlprotocol setProperty:@YES forkey:urlprotocolhandledkey Inrequest:mutablereqeust];

self. Connection = [nsurlconnection connectionwithrequest:mutablereqeust Delegate: Self ];

}

- (void)stoploading

{

[self. Connection Cancel];

}

    • Nsurlconnectiondatadelegate method

      The proxy method is called when processing a network request, and we need to return the received message to the URL Loading System via the client.

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

}

Now that you can intercept the request and do what you want to do, here's a demo:https://github.com/freemind-lj/nsurlprotocolexample.

can refer to, intercept request and redirect to the new address, the specific DNS resolution method can refer to DNS resolution (HTTP://WWW.JIANSHU.COM/P/D945454E3ABC), if not, please correct, ah ~

IOS Development-nsurlprotocol

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.