利用AFNetworking 的AFHTTPSessionManager代码实现代理的方式访问任意指定IP地址,解决域名DNS上的问题

以下仅将关键代码列出供参与学习使用,在网络请求方面

AFHTTPSessionManager 和AFHTTPRequestOperationManager 两个相比在代码实现方式及请求原理上差不太多(包括在RAC的支持上).

但在代理服务上AFHTTPSessionManager支持很好,AFHTTPRequestOperationManager目前不支持:

以下是AFHTTPSessionManager代理实现方式:


@property(nonatomic,strong)AFHTTPSessionManager *manager; //AF请求对象

#pragma mark httpMode
/**
 * 初始化HTTP
 */
- (void)httpInit
{
    //获取实例对象
    //self.manager = [AFHTTPSessionManager manager];
    
    //设置代理并获取实例对象
    self.manager = [[AFHTTPSessionManager manager] initWithBaseURL:nil sessionConfiguration:[self setProxyWithConfig]];
    
    //申明返回的结果是JSON类型
    self.manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    //如果报接受类型不一致请替换一致text/html
    self.manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    
    //清求时间设置
    self.manager.requestSerializer.timeoutInterval = 30;
    
    //添加header头信息
    [self addRequestHeader];
}

/**
 * 代理设置
 */
- (NSURLSessionConfiguration *)setProxyWithConfig
{
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
    config.connectionProxyDictionary = @
    {
        @"HTTPEnable":@YES,
        (id)kCFStreamPropertyHTTPProxyHost:@"127.0.0.1",
        (id)kCFStreamPropertyHTTPProxyPort:@80,
        @"HTTPSEnable":@YES,
        (id)kCFStreamPropertyHTTPSProxyHost:@"127.0.0.1",
        (id)kCFStreamPropertyHTTPSProxyPort:@80
    };
    
    return config;
}

通过以下方式即可实现代理的请求,至于后续的GET POST UPLOAD DOWNLOAD 自己根据实际情况封装实现一下就可以,

下面是用GET方的请求,同时实现的NSURLCache实现对所请求数据的缓存处理

/**
 * 发送getCache请求
 */
- (void)startCache:(NSString *)uri tag:(NSInteger)tag
{
    [self httpInit];
    
    //根据url生成cache数据
    NSURLRequest *aRequestKey = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",self.baseUrl,uri]]];
    
    NSLog(@"%@",[NSString stringWithFormat:@"%@%@",self.baseUrl,uri]);
    
    //获取并缓存cache
    __weak typeof(self)weakSelf = self;
    [self.manager GET:[NSString stringWithFormat:@"%@%@",self.baseUrl,[self getUriWithTime:uri]] parameters:nil success:^(NSURLSessionDataTask *task,id responseObject) {
            [weakSelf requestFinished:responseObject tag:tag];
        
        //将获取的数据缓存缓存cache数据
        if ([weakSelf.errCode intValue] <= 0 && [NSJSONSerialization isValidJSONObject:responseObject]) {
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
            NSCachedURLResponse *cachedURLResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:aRequestKey];
            cachedURLResponse = [[NSCachedURLResponse alloc] initWithResponse:task.response data:jsonData userInfo:nil storagePolicy:NSURLCacheStorageAllowed];
            [[NSURLCache sharedURLCache] storeCachedResponse:cachedURLResponse forRequest:aRequestKey];
        } else {
            
            [weakSelf requestFailed:tag];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        NSCachedURLResponse *cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:aRequestKey];
        if (cachedResponse != nil && [[cachedResponse data] length] > 0) {
            NSDictionary *cachedDic = [NSJSONSerialization JSONObjectWithData:[cachedResponse data] options:NSJSONReadingMutableContainers error:nil];
            
            [weakSelf requestFinished:cachedDic tag:tag];
        }else{
            [weakSelf requestFailed:tag];
        }
    }];
}








  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值