issue: Domain name hijacking due to DNS requires manually redirecting URL requests to the specified IP addressRecently 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
- Block load request, switch to load from local file
- Some global network request settings
- Fast switching of test environments
- Filter out some illegal requests
- Network cache processing (H5 offline packages and network picture caches)
- Can intercept UIWebView, based on the system's Nsurlconnection or nsurlsession for encapsulating network requests. Currently Wkwebview cannot be intercepted by Nsurlprotocol.
- When multiple custom nsurlprotocol are registered to the system, the URL loading process is called sequentially in the reverse order in which they are registered. When one of the Nsurlprotocol intercepts the request, the subsequent nsurlprotocol cannot intercept the request.
Intercept network request 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 class ]]; return YES;}
Implement Customurlprotocol
#import " CustomURLProtocol.h " Static Const @" Urlprotocolhandledkey " ; @interface Customurlprotocol () <NSURLConnectionDelegate>*connection; @end @implementation Customurlprotocol // Here's the way to write the rewrite. @end
Once you're signed up, you can now start implementing some of the Nsurlprotocol methods:
- +canonicalrequestforrequest If there is no special requirement, return to request directly, you can modify the request in the Startloading method in the start load, such as adding header, modifying host, requesting redirect, etc.
+ (Nsurlrequest *) Canonicalrequestforrequest: (Nsurlrequest *) Request { 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];}
- 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];}//Resolve HTTPS Request certificate validation for sending IP addresses- (void) Connection: (Nsurlconnection *) connection Willsendrequestforauthenticationchallenge: ( Nsurlauthenticationchallenge *) challenge{if(!Challenge) { return; } if([Challenge.protectionSpace.authenticationMethod isequaltostring:nsurlauthenticationmethodservertrust]) { /c8>//constructs a nsurlcredential sent to the initiatorNsurlcredential *credential =[Nsurlcredential CredentialForTrust:challenge.protectionSpace.serverTrust]; [[Challenge Sender] usecredential:credential Forauthenticationchallenge:challenge]; } Else { //Process processes directly for other validation methods[[Challenge Sender] continuewithoutcredentialforauthenticationchallenge:challenge]; }}
Attention?? : This will require verifying the certificate for HTTPS request when manually redirecting the URL request to the specified IP address to request
IOS Nsurlprotocol Detailed and applied