网络请求封装

//
//  ASIHTTPRequest+Request.h
//  CloudShopping
//
//  Created by sixiaobo on 14-7-9.
//  Copyright (c) 2014年 com.Uni2uni. All rights reserved.
//

#import "ASIFormDataRequest.h"
#import "ASIDownloadCache.h"

// downloadData是返回的数据,如果出错,会把错误放到error中,否则error为nil,可通过error参数
// 判断是否出错
typedef void(^HYBResultBlock)(NSData *downloadData, NSError *error);

//
// HYBRequestType枚举用于指定请求类型
typedef NS_ENUM(NSUInteger, HYBRequestType) {
    kTypePost = 1 << 1,  // POST请求
    kTypeGet  = 1 << 2   // GET请求
};


@interface HYBHttpRequest : ASIFormDataRequest 

// 请求回调block,成功或者失败都会回调此block,通过error参数判断是否成功
@property (nonatomic, copy)   HYBResultBlock resultBlock;
@property (nonatomic, strong) NSMutableData  *downloadData;       // 下载完成后的数据
@property (nonatomic, assign) HYBRequestType requestType;


// 异步请求方式

/*!
 * @brief 默认使用POST请求方式
 * @param path 网络请求前缀参数
 * @param params 使用字典存储,会在内部拼接到请求网址中
 * @param completion 完成时的回调block
 * @return 返回HYBHttpRequest对象
 */
- (id)initWithPath:(NSString *)path
            params:(NSDictionary *)params
        completion:(HYBResultBlock)completion;
 
- (id)initWithPath:(NSString *)path
            params:(NSDictionary *)params
       requestType:(HYBRequestType)requestType
        completion:(HYBResultBlock)completion;
- (id)initWithPath:(NSString *)path
       requestType:(HYBRequestType)requestType
        completion:(HYBResultBlock)completion;

// 必须是POST请求,请求参数要转换成JSON格式数据
- (id)initWithPath:(NSString *)path
          postBody:(NSMutableData *)postBodyJSONData
        completion:(HYBResultBlock)completion;
// 取消请求
- (void)cancelRequest;

@end


//
//  ASIHTTPRequest+Request.m
//  CloudShopping
//
//  Created by sixiaobo on 14-7-9.
//  Copyright (c) 2014年 com.Uni2uni. All rights reserved.
//

#import "HYBHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "NSString+Common.h"
#import "HYBHttpRequestManager.h"
#import "NSString+Encrypt.h"

@implementation HYBHttpRequest

- (id)initWithPath:(NSString *)path
            params:(NSDictionary *)params
       requestType:(HYBRequestType)requestType
        completion:(HYBResultBlock)completion {
    if (self = [super initWithURL:[NSURL URLWithString:path]]) {
        self.delegate = self;
        self.resultBlock = [completion copy];
        self.downloadData = [[NSMutableData alloc] init];
        self.requestType = requestType;
        
        // 缓存有效期为一天
        [self setSecondsToCache:24 * 60 * 60];
        self.timeOutSeconds = 60;
        [self setNumberOfTimesToRetryOnTimeout:2]; // 设置超时时重发次数为3
        self.shouldContinueWhenAppEntersBackground = YES;
        
        // 需要保证ASIDownloadCache对象都不会释放
        if ([HYBHttpRequestManager sharedRequestManager].downloadCache == nil) {
            ASIDownloadCache *cache = nil;
            cache = [[ASIDownloadCache alloc] init];
            cache.defaultCachePolicy = ASIOnlyLoadIfNotCachedCachePolicy;
            cache.storagePath = [NSString cachePath];
            // 放到单例中管理
            [[HYBHttpRequestManager sharedRequestManager] setDownloadCache:cache];
        }
        ASIDownloadCache *cache = [HYBHttpRequestManager sharedRequestManager].downloadCache;
        self.cacheStoragePolicy = ASICachePermanentlyCacheStoragePolicy;
        self.downloadCache = cache;
        
        
        if (self.requestType == kTypeGet) {
            [self setRequestMethod:@"GET"];
              [self didUseCachedResponse];
            // 设置永久存储在本地
        } else if (self.requestType == kTypePost) {
            [self setRequestMethod:@"POST"];
            [self addRequestHeader:@"Content-Type" value:@"application/json"];
            if (params) {
                for (NSString *key in params.allKeys) {
                    [self addPostValue:[params objectForKey:key] forKey:key];
                }
            }
            [self didUseCachedResponse];
        }
        
        [[HYBHttpRequestManager sharedRequestManager] addRequest:self
                                                         withKey:self.url.absoluteString.md5];
        [self startAsynchronous];
    }
    return self;
}

- (id)initWithPath:(NSString *)path params:(NSDictionary *)params completion:(HYBResultBlock)completion {
    return [self initWithPath:path params:params requestType:kTypePost completion:completion];
}

- (id)initWithPath:(NSString *)path
        completion:(HYBResultBlock)completion {
    return [self initWithPath:path params:nil completion:completion];
}

- (id)initWithPath:(NSString *)path
       requestType:(HYBRequestType)requestType
        completion:(HYBResultBlock)completion {
    return [self initWithPath:path params:nil requestType:requestType completion:completion];
}

// 必须是POST请求,请求参数要转换成JSON格式数据
- (id)initWithPath:(NSString *)path
          postBody:(NSMutableData *)postBodyJSONData
        completion:(HYBResultBlock)completion {
    if (self = [super initWithURL:[NSURL URLWithString:path]]) {
        self.delegate = self;
        self.resultBlock = [completion copy];
        self.downloadData = [[NSMutableData alloc] init];
        self.requestType = kTypePost;
        
        // 缓存有效期为一天
        [self setSecondsToCache:24 * 60 * 60];
        self.timeOutSeconds = 60;
        [self setNumberOfTimesToRetryOnTimeout:2]; // 设置超时时重发次数为3
        self.shouldContinueWhenAppEntersBackground = YES;
        
        // 需要保证ASIDownloadCache对象都不会释放
        if ([HYBHttpRequestManager sharedRequestManager].downloadCache == nil) {
            ASIDownloadCache *cache = nil;
            cache = [[ASIDownloadCache alloc] init];
            cache.defaultCachePolicy = ASIOnlyLoadIfNotCachedCachePolicy;
            cache.storagePath = [NSString cachePath];
            // 放到单例中管理
            [[HYBHttpRequestManager sharedRequestManager] setDownloadCache:cache];
        }
        ASIDownloadCache *cache = [HYBHttpRequestManager sharedRequestManager].downloadCache;
        self.cacheStoragePolicy = ASICachePermanentlyCacheStoragePolicy;
        self.downloadCache = cache;
        
        if (self.requestType == kTypePost) {
            [self setRequestMethod:@"POST"];
            [self addRequestHeader:@"Content-Type" value:@"application/json"];
            [self addRequestHeader:@"Accept" value:@"application/json"];
            [self setPostBody:postBodyJSONData];
            [self didUseCachedResponse];
        }
        
        // 自动管理请求对象的生命周期
        [[HYBHttpRequestManager sharedRequestManager] addRequest:self
                                                         withKey:self.url.absoluteString.md5];
        [self startAsynchronous];
    }
    return self;
}

- (void)cancelRequest {
    [self clearDelegatesAndCancel];
    return;
}

#pragma mark - ASIHttpRequestDelegate
- (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders {
    [self.downloadData setLength:0];
    return;
}

- (void)requestFinished:(ASIHTTPRequest *)request {
    [[HYBHttpRequestManager sharedRequestManager] removeRequestWithKey:self.url.absoluteString.md5];
    if (self.resultBlock) {
        self.resultBlock(self.downloadData, nil);
    }
    return;
}

- (void)requestFailed:(ASIHTTPRequest *)request {
    [[HYBHttpRequestManager sharedRequestManager] removeRequestWithKey:self.url.absoluteString.md5];
    if (self.resultBlock) {
        [self clearDelegatesAndCancel];
        self.resultBlock(self.downloadData, self.error);
    }
    return;
}

- (void)request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data {
    [self.downloadData appendData:data];
    return;
}

@end


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值