IOS Nsurlprotocol Detailed and applied

Source: Internet
Author: User

  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:

  • +caninitwithrequest:
    This method is mainly to indicate whether you intend to deal with the corresponding request, if you do not intend to deal with it,returns No,url Loading system uses the default behavior of the systems to processIf you intend to deal with it,returns Yes, and then you need to process everything for that request, including getting the request data and returning it to the URL Loading System。

    network data can be easily obtained through nsurlconnection.Andeach Nsurlprotocol object has a nsurlprotocolclient instanceOKThe data obtained by the client is returned to the URL 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 shouldensure that each request is processed only once, you can identify the request that has already been processed by +setproperty:forkey:inrequest, and then, in +caninitwithrequest:, query whether the request has already been processed, or return no if it is.
    + (BOOL) Caninitwithrequest: (Nsurlrequest *) request{//processing HTTP and HTTPS requests only returns no default to the system to processNSString *scheme =[[Request URL] scheme]; if([Scheme Caseinsensitivecompare:@"http"] = = Nsorderedsame | |[Scheme caseinsensitivecompare:@"HTTPS"] ==nsorderedsame)) {        //See if it has been processed to prevent infinite loops from being intercepted by the business        if([Nsurlprotocol propertyforkey:urlprotocolhandledkey inrequest:request]) {returnNO; }             //also here intercept the link in the DSN resolution request to determine the link of the blocked domain name request if it returns no         if(the link that determines the blocked domain name request) {returnNO; }                returnYES; }    returnNO;}

    • +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];}

  • -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]; //flag Change request has been processed to prevent an infinite loop[nsurlprotocol setProperty: @YES forkey:urlprotocolhandledkey inrequest:mutablereqeust]; // redirectSelf.connection = [Nsurlconnection connectionwithrequest:[self dealdns:mutablereqeust]Delegate: self];}- (void) stoploading{[self.connection Cancel]; Self.connection=Nil;}//Resolve hijacking Redirect to IP address-(Nsmutableurlrequest *) Dealdns: (Nsmutableurlrequest *) request{if([Request. URL Host].length = =0) {            returnrequest; } nsstring*originurlstring =[Request.    URL absolutestring]; NSString*originhoststring =[Request.    URL host]; Nsrange Hostrange=[originurlstring rangeofstring:originhoststring]; if(Hostrange.location = =nsnotfound) {        returnrequest; }     //Obtain an IP (such as 172.128.3.3) and replace it with a URL based on the current host (such as baidu.com) request//directed to IP change IP needs to be requested according to the host to obtain theNSString *ip = obtained according to host request;//(such as baidu.com) Sync request get to IP (like 172.128.3.3) Note?? The link to this request needs to be filtered out of the caninitwithrequest.//Replace domain name//URL:https://www.baidu.comreplaced with https://172.128.3.3NSString *urlstring =[originurlstring Stringbyreplacingcharactersinrange:hostrange Withstring:ip]; Nsurl*url =[Nsurl urlwithstring:urlstring]; Request. URL=URL; //set a cookie to change IP[Cookiemanager SetWebViewCookieForDomain:ipUrl.host]; returnrequest;}

    • 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

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.