This is the 12th day of my participation in the August More Text Challenge. For details, see “August More Text Challenge” juejin.cn/post/698796…

The introduction

The user feedback before Naruto demo:download.csdn.net/download/u0 today… It’s a bit complicated, because the requirement is to automatically intercept HTTP requests by dragging my custom NSURLProtocol subclass into the dynamic library.

In response to his request, I specially wrote a simple demo today.

In fact, the original manual registration of our protocol class, using a small trick, using the form of classification in the load method for automatic registration

Currently, as soon as you load the NSURL class, demo will automatically inject my custom NSURLProtocol subclass for HTTP interception. Of course, you can switch to another class, not necessarily NSURL (as long as you think it will trigger).

In this paper, the demo download.csdn.net/download/u0 download address…

I, the principle of

1. Intercepting requests based on NSURLProtocol:

When an HTTP request starts, the URL loading system creates an appropriate NSURLProtocol object to handle the corresponding URL request, so we simply write a class that inherits from NSURLProtocol and registerClass via -registerClass: Method to register our protocol class, and the URL loading system will process the request when it is issued using the protocol object we created.

2. Automatically register protocol classes in the form of classification in the load method

Intercepts HTTP requests based on NSURLProtocol

  • Custom NSURLProtocol subclass
  • [KNURLProtocol shareInstance]. RequestBlock =; Because intercepted requests are given to the requestBlockForRequst for processing; You can print the request information in this block for debugging validation
  • Registration Protocol class:

Method 1: When the app starts, call the addRequestBlock method of KNURLProtocol. Method 2: Automatically register the protocol classes in the load method in the form of classification (for dynamic library/static library projects).

2.1 Automatically register protocol classes in the form of classification in the Load method

#import "NSURL+registerURLProtocolClass.h"

@implementation NSURL (registerURLProtocolClass)+ (void)load{
    [super load];
 
    
    [self requestBlock];
    
}


#pragmaMark intercepts global requests
+ (void)requestBlock{
    [KNURLProtocol handleRequest:^NSURLRequest* (NSURLRequest *request) {
        
        
        NSLog(@" Intercepted request -%@",request);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
// self.blocktv. text = [self.blocktv. text stringByAppendingString:[NSString stringWithFormat:@" intercepting the request --%@\n",request]];
        });
        
        return request;
    }];
    
}

Copy the code

Custom NSURLProtocol subclass

  • Core method
/** Determine whether the request needs to be handled by the current protocol object. A: Yes, you can write your own switch or define your own interception rules. Currently, Demo only determines the URL to register isUrl protocol class. You can automatically register isUrl protocol class in the form of classification in the load method */+ (BOOL)canInitWithRequest:(NSURLRequest *)request{
    
    
    if ([NSURLProtocol propertyForKey:protocolKey inRequest:request]) {
        return NO;
    }
    NSString * url = request.URL.absoluteString;
    return [self isUrl:url];
}

/** What needs to be done with the current request object */+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
    return[[KNURLProtocol shareInstance] requestBlockForRequst:request]; } - (NSURLRequest *)requestBlockForRequst:(NSURLRequest *)request{
    if(self.requestBlock){
        return self.requestBlock(request);
    }else{
        returnrequest; }}Copy the code
  • KNURLProtocol.h
//
// KNURLProtocol.h
// KNURLProtocolDemo
//
// Created by mac on 2021/4/19.
//

#import <Foundation/Foundation.h>
#import "HSSingleton.h"
typedef NSURLRequest *(^requestBlock) (NSURLRequest *request);

NS_ASSUME_NONNULL_BEGIN

@interface KNURLProtocol : NSURLProtocol

@property (nonatomic.copy) NSURLRequest *(^requestBlock)(NSURLRequest *request);


HSSingletonH(Instance);



/** Intercept the global request @param block request callback, the block returns the modified request */+ (void)handleRequest:(requestBlock)block;

/** Disable all network requests */+ (void)cancelAllRequest;

/** Restore all network requests */+ (void)resumeAllRequest;






@end

NS_ASSUME_NONNULL_END

Copy the code
  • KNURLProtocol.m

More content in the original: blog.csdn.net/z929118967/…

Welcome to the public account: iOS Reverse

see also

  • Create the entry for the category

  • Before the demo please look at this article: kunnan.blog.csdn.net/article/det…

From CSDN download demo resources: 1, article: https://download.csdn.net/download/u011018979/16768533 kunnan.blog.csdn.net/article/det…

2. Application Scenario:

2.1. Customize HTTPHeaderField for request headers

2.2, against NSURLSessionConfiguration agents set up IP and port, make some special request custom tunnel IP and port

2.3. Packet level encryption for network request data: NSURLProtocol is used to automatically listen for HTTP requests, encrypt and decrypt them.

[NSURLProtocol registerClass: [NetworkInject Class]]; The custom NSURLProtocol class is injected

3. Principle: Use NSURLProtocol to intercept HTTP requests based on NSURLProtocol to realize the interception of all network requests at the bottom of iOS applications (including web page Ajax request interception [does not support WKWebView]); When an HTTP request starts, the URL loading system creates an appropriate NSURLProtocol object to handle the corresponding URL request, so we simply write a class that inherits from NSURLProtocol and registerClass via -registerClass: Method to register our protocol class, and the URL loading system will process the request when it is issued using the protocol object we created.

4. Features:

4.1 HTTP-DNS Prevents DNS hijacking.

DNS resolution is performed directly from the local or specific server address, which is a measure to avoid DNS hijacking

Kunnan.blog.csdn.net/article/det…

4.2 ban caught network (open after use proxy way caught program to catch the request in the App, and timing under agency network will not affect the request of the App itself) kunnan.blog.csdn.net/article/det…