网络请求全部转成HTTPS请求的方式

通过runtime运行机制,交换方法的实现。

+ (NSString *)HTTPTransToHTTPS:(NSString *)url

{

    NSError * error = nil;

    NSString * urlString = url;

    NSRegularExpression * regex = [[NSRegularExpression alloc]initWithPattern:@"^http:" options:NSRegularExpressionCaseInsensitive error:&error];

    urlString = [regex stringByReplacingMatchesInString:urlString options:NSMatchingReportProgress range:NSMakeRange(0, urlString.length) withTemplate:@"https:"];

    return  urlString;

 

}

 

#import "NSURL+HTTPS.h"

#import <objc/runtime.h>

#import <objc/message.h>

 

@implementation NSURL (HTTPS)

 

+ (void)initialize

{

    

    Method  method_pre = class_getClassMethod(self,@selector(URLWithString:relativeToURL:));

    Method  method_cur = class_getClassMethod(self,@selector(p_URLWithString:relativeToURL:));

    if(method_cur&&method_pre)

    {

        method_exchangeImplementations(method_pre, method_cur);

    }

}

 

+ (instancetype)p_URLWithString:(NSString *)URLString relativeToURL:(NSURL *)baseURL

{

    NSError * error = nil;

    NSString * urlString = URLString;

    NSRegularExpression * regex = [[NSRegularExpression alloc]initWithPattern:@"^http:" options:NSRegularExpressionCaseInsensitive error:&error];

    urlString = [regex stringByReplacingMatchesInString:urlString options:NSMatchingReportProgress range:NSMakeRange(0, urlString.length) withTemplate:@"https:"];

    return [self p_URLWithString:urlString relativeToURL:baseURL];

    

}

posted @ 2017-04-01 10:53  tiankongzhicheng  阅读(328)  评论(0编辑  收藏  举报