对ASIHTTPRequest的封装

版权声明:本文为博主原创文章。未经博主同意不得转载。

https://blog.csdn.net/quanqinayng/article/details/37659751

.h文件 

//
//  HttpUtil.h
//  SmallTaurus
//
//  Created by Fuer on 14-7-7.
//  Copyright (c) 2014年 FuEr. All rights reserved.
//
/**
 *  对ASI的封装
 */
#import <Foundation/Foundation.h>
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
/**
 *  Debug_LOG信息控制;
 *
 *  IS_ENABLE_DEBUG_LOG 设置为 1 ,打印请求log基本信息;
 *  IS_ENABLE_DEBUG_LOG 设置为 0 ,不打印请求log基本信息;
 */
#define IS_ENABLE_DEBUG_LOG 1

#if IS_ENABLE_DEBUG_LOG
#define kDEBUG_LOG() NSLog(@"line:(%d),%s",__LINE__,__FUNCTION__)
#define kNSLog(...)  NSLog(__VA_ARGS__)
#else
#define kDEBUG_LOG()
#define kNSLog(...)
#endif

extern NSString *const kAPI_BASE_URL;

/**
 *  ASICLient 请求回调的块声明。
 *
 *  主要的请求完毕,失败,上传及下载进度 Block回调;
 */
typedef void (^KKCompletedBlock)(id JSON,NSString *stringData);
typedef void (^KKFailedBlock)(NSError *error);
typedef void (^KKProgressBlock)(float progress);


@interface HttpUtil : NSObject
+(HttpUtil*)shareInstance;
/**
 *  一般的get请求,无參数;
 *
 *  @param path          接口路径。不能为空;
 *  @param completeBlock 请求完毕块。返回 id JSON, NSString *stringData;
 *  @param failed        请求失败块。返回 NSError *error;
 *
 *  @return 返回ASIHTTPRequest的指针,可用于 NSOperationQueue操作。
 */
+ (ASIHTTPRequest *)GET_Path:(NSString *)path completed:(KKCompletedBlock )completeBlock failed:(KKFailedBlock )failed;

/**
 *  一般的GET请求。有參数。
 *
 *  @param path          接口路径,不能为空;
 *  @param paramsDic     请求的參数的字典,參数可为nil, 比如:NSDictionary *params = @{@"key":@"value"}
 *  @param completeBlock 请求完毕块,返回 id JSON, NSString *stringData;
 *  @param failed        请求失败块,返回 NSError *error;
 *
 *  @return 返回ASIHTTPRequest的指针,可用于 NSOperationQueue操作
 */
+ (ASIHTTPRequest *)GET_Path:(NSString *)path params:(NSDictionary *)paramsDic completed:(KKCompletedBlock )completeBlock failed:(KKFailedBlock )failed;

/**
 *  一般的POST请求,有參数;
 *
 *  @param path          接口路径。不能为空。
 *  @param paramsDic     请求的參数的字典,參数可为nil, 比如:NSDictionary *params = @{@"key":@"value"}
 *  @param completeBlock 请求完毕块。返回 id JSON, NSString *stringData;
 *  @param failed        请求失败块,返回 NSError *error;
 *
 *  @return 返回ASIHTTPRequest的指针。可用于 NSOperationQueue操作
 */
+ (ASIHTTPRequest *)POST_Path:(NSString *)path params:(NSDictionary *)paramsDic completed:(KKCompletedBlock )completeBlock failed:(KKFailedBlock )failed;

/**
 *  一般GET请求下载文件;
 *
 *  @param path           接口路径,不能为空;
 *  @param destination    下载文件保存的路径,不能为空;
 *  @param name           下载文件保存的名字,不能为空;
 *  @param progressBlock  下载文件的Progress块,返回 float progress,在此跟踪下载进度。
 *  @param completeBlock  请求完毕块,无返回值。
 *  @param failed         请求失败块,返回 NSError *error;
 *
 *  @return 返回ASIHTTPRequest的指针,可用于 NSOperationQueue操作
 */
+ (ASIHTTPRequest *)DownFile_Path:(NSString *)path writeTo:(NSString *)destination fileName:(NSString *)name setProgress:(KKProgressBlock)progressBlock completed:(ASIBasicBlock)completedBlock failed:(KKFailedBlock )failed;


/**
 *  一般的POST上传文件;
 *
 *  @param path           上传接口路径。不能为空;
 *  @param filePath       要上传的文件路径,不能为空;
 *  @param fileKey        上传文件相应server接收的key,不能为空;
 *  @param params         请求的參数的字典,參数可为nil, 比如:NSDictionary *params = @{@"key":@"value"}
 *  @param progressBlock  上传文件的Progress块,返回 float progress,在此跟踪下载进度;
 *  @param completeBlock  请求完毕块,返回 id JSON, NSString *stringData;
 *  @param failed         请求失败块,返回 NSError *error;
 *
 *  @return 返回ASIHTTPRequest的指针,可用于 NSOperationQueue操作
 */
+ (ASIHTTPRequest *)UploadFile_Path:(NSString *)path file:(NSString *)filePath forKey:(NSString *)fileKey params:(NSDictionary *)params SetProgress:(KKProgressBlock )progressBlock completed:(KKCompletedBlock )completedBlock failed:(KKFailedBlock )failed;


/**
 *  一般的POST数据Data上传。
 *
 *  @param path           上传接口路径。不能为空;
 *  @param fData          要上传的文件Data,不能为空;
 *  @param dataKey        上传的Data相应server接收的key,不能为空;
 *  @param params         请求的參数的字典,參数可为nil, 比如:NSDictionary *params = @{@"key":@"value"}
 *  @param progressBlock  上传文件的Progress块,返回 float progress,在此跟踪下载进度。
 *  @param completeBlock  请求完毕块,返回 id JSON, NSString *stringData;
 *  @param failed         请求失败块。返回 NSError *error;
 *
 *  @return 返回ASIHTTPRequest的指针,可用于 NSOperationQueue操作
 */
+ (ASIHTTPRequest *)UploadData_Path:(NSString *)path fileData:(NSData *)fData forKey:(NSString *)dataKey params:(NSDictionary *)params SetProgress:(KKProgressBlock )progressBlock completed:(KKCompletedBlock )completedBlock failed:(KKFailedBlock )failed;


/**
 *  文件下载。支持断点续传功能;
 *
 *  @param path            接口路径,不能为空;
 *  @param destinationPath 下载文件要保存的路径。不能为空;
 *  @param tempPath        暂时文件保存的路径。不能为空;
 *  @param name            下载保存的文件名称。不能为空。
 *  @param progressBlock   下载文件的Progress块。返回 float progress,在此跟踪下载进度。
 *  @param completedBlock  下载完毕回调块,无回返值。
 *  @param failed          下载失败回调块,返回 NSError *error;
 *
 *  @return 返回ASIHTTPRequest的指针,可用于 NSOperationQueue操作
 */
+ (ASIHTTPRequest *)ResumeDown_Path:(NSString *)path writeTo:(NSString *)destinationPath tempPath:(NSString *)tempPath fileName:(NSString *)name setProgress:(KKProgressBlock )progressBlock completed:(ASIBasicBlock )completedBlock failed:(KKFailedBlock )failed;


/*
 安装:配置
 1:所需frame.work;
 CFNetwork, SystemConfiguration, MobileCoreServices, CoreGraphics and libz.dylib  libxml2.dylib
 2: ASI Tests 须要 https://github.com/gh-unit/gh-unit/tree/master 然后导入 :GHUnitIOS.framework
 3:bulid setting  Header search path 加入 /usr/include/libxml2
 4:在 test/ASIDataCompareTest.m中有个 NStask错误,删除文件就可以;
 5: 假设使用 Test文件加里面的东西。使用 GHUnitIOS.framework http://stackoverflow.com/questions/13925437/ghunitios-ghunit-h-file-not-found-in-xcode
 
 官方文档:http://allseeing-i.com/ASIHTTPRequest/How-to-use
 
 */
@end

.m文件

//
//  HttpUtil.m
//  SmallTaurus
//
//  Created by Fuer on 14-7-7.
//  Copyright (c) 2014年 FuEr. All rights reserved.
//

#import "HttpUtil.h"
NSString *const kAPI_BASE_URL = @"http://api.douban.com/v2/";

@implementation HttpUtil
+(HttpUtil*)shareInstance
{
    static HttpUtil *httpUtil = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        httpUtil = [[HttpUtil alloc]init];
    });
    return httpUtil;
}
+ (ASIHTTPRequest *)GET_Path:(NSString *)path completed:(KKCompletedBlock )completeBlock failed:(KKFailedBlock )failed
{
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",kAPI_BASE_URL,path];
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlStr];
    __weak ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    request.requestMethod = @"GET";
    
    [request setCompletionBlock:^{
        NSError *errorForJSON = [NSError errorWithDomain:@"请求数据解析为json格式。发出错误" code:2014 userInfo:@{@"请求数据json解析错误": @"中文",@"serial the data to json error":@"English"}];
        id jsonData = [NSJSONSerialization JSONObjectWithData:[request responseData] options:0 error:&errorForJSON];
        completeBlock(jsonData,request.responseString);
    }];
    
    [request setFailedBlock:^{
        failed([request error]);
    }];
    
    [request startAsynchronous];
    
    kNSLog(@"ASIClient GET: %@",[request url]);
    
    return request;
}

+ (ASIHTTPRequest *)GET_Path:(NSString *)path params:(NSDictionary *)paramsDic completed:(KKCompletedBlock )completeBlock failed:(KKFailedBlock )failed
{
    NSMutableString *paramsString = [NSMutableString stringWithCapacity:1];
    [paramsDic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        [paramsString appendFormat:@"%@=%@",key,obj];
        [paramsString appendString:@"&"];
    }];
    NSString *urlStr = [NSString stringWithFormat:@"%@%@?%@",kAPI_BASE_URL,path,paramsString];
    urlStr = [urlStr substringToIndex:urlStr.length-1];
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *url = [NSURL URLWithString:urlStr];
    __weak ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    request.requestMethod = @"GET";
    
    [request setCompletionBlock:^{
        NSError *errorForJSON = [NSError errorWithDomain:@"请求数据解析为json格式,发出错误" code:2014 userInfo:@{@"请求数据json解析错误": @"中文",@"serial the data to json error":@"English"}];
        id jsonData = [NSJSONSerialization JSONObjectWithData:[request responseData] options:0 error:&errorForJSON];
        completeBlock(jsonData,request.responseString);
    }];
    
    [request setFailedBlock:^{
        failed([request error]);
    }];
    
    [request startAsynchronous];
    
    kNSLog(@"ASIClient GET: %@",[request url]);
    
    return request;
}


+ (ASIHTTPRequest *)POST_Path:(NSString *)path params:(NSDictionary *)paramsDic completed:(KKCompletedBlock )completeBlock failed:(KKFailedBlock )failed
{
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",kAPI_BASE_URL,path];
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlStr];
    __weak ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    request.requestMethod = @"POST";
    
    [paramsDic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        [request setPostValue:obj forKey:key];
    }];
    
    [request setCompletionBlock:^{
        NSError *errorForJSON = [NSError errorWithDomain:@"请求数据解析为json格式,发出错误" code:2014 userInfo:@{@"请求数据json解析错误": @"中文",@"serial the data to json error":@"English"}];
        id jsonData = [NSJSONSerialization JSONObjectWithData:[request responseData] options:0 error:&errorForJSON];
        completeBlock(jsonData,request.responseString);
    }];
    
    [request setFailedBlock:^{
        failed([request error]);
    }];
    
    [request startAsynchronous];
    
    kNSLog(@"ASIClient POST: %@ %@",[request url],paramsDic);
    
    return request;
}


+ (ASIHTTPRequest *)DownFile_Path:(NSString *)path writeTo:(NSString *)destination fileName:(NSString *)name setProgress:(KKProgressBlock)progressBlock completed:(ASIBasicBlock)completedBlock failed:(KKFailedBlock )failed
{
    __weak ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:path]];
    NSString *filePath = nil;
    if ([destination hasSuffix:@"/"]) {
        filePath = [NSString stringWithFormat:@"%@%@",destination,name];
    }
    else
    {
        filePath = [NSString stringWithFormat:@"%@/%@",destination,name];
    }
    [request setDownloadDestinationPath:filePath];
    
    __block float downProgress = 0;
    [request setBytesReceivedBlock:^(unsigned long long size, unsigned long long total) {
        downProgress += (float)size/total;
        progressBlock(downProgress);
    }];
    
    [request setCompletionBlock:^{
        downProgress = 0;
        completedBlock();
    }];
    
    [request setFailedBlock:^{
        failed([request error]);
    }];
    
    [request startAsynchronous];
    
    kNSLog(@"ASIClient 下载文件:%@ ",path);
    kNSLog(@"ASIClient 保存路径:%@",filePath);
    
    return request;
}


+ (ASIHTTPRequest *)UploadFile_Path:(NSString *)path file:(NSString *)filePath forKey:(NSString *)fileKey params:(NSDictionary *)params SetProgress:(KKProgressBlock )progressBlock completed:(KKCompletedBlock )completedBlock failed:(KKFailedBlock )failed
{
    
    NSURL *url = [NSURL URLWithString:path];
    __weak ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    [request setFile:filePath forKey:fileKey];
    if (params.count > 0) {
        [params enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            [request setPostValue:obj forKey:key];
        }];
    }
    
    __block float upProgress = 0;
    [request setBytesSentBlock:^(unsigned long long size, unsigned long long total) {
        upProgress += (float)size/total;
        progressBlock(upProgress);
    }];
    
    [request setCompletionBlock:^{
        upProgress=0;
        NSError *errorForJSON = [NSError errorWithDomain:@"请求数据解析为json格式。发出错误" code:2014 userInfo:@{@"请求数据json解析错误": @"中文",@"serial the data to json error":@"English"}];
        id jsonData = [NSJSONSerialization JSONObjectWithData:[request responseData] options:0 error:&errorForJSON];
        completedBlock(jsonData,[request responseString]);
    }];
    
    [request setFailedBlock:^{
        failed([request error]);
    }];
    
    [request startAsynchronous];
    
    kNSLog(@"ASIClient 文件上传:%@ file=%@ key=%@",path,filePath,fileKey);
    kNSLog(@"ASIClient 文件上传參数:%@",params);
    
    return request;
}


+ (ASIHTTPRequest *)UploadData_Path:(NSString *)path fileData:(NSData *)fData forKey:(NSString *)dataKey params:(NSDictionary *)params SetProgress:(KKProgressBlock )progressBlock completed:(KKCompletedBlock )completedBlock failed:(KKFailedBlock )failed
{
    NSURL *url = [NSURL URLWithString:path];
    __weak ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    [request setData:fData forKey:dataKey];
    if (params.count > 0) {
        [params enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            [request setPostValue:obj forKey:key];
        }];
    }
    
    __block float upProgress = 0;
    [request setBytesSentBlock:^(unsigned long long size, unsigned long long total) {
        upProgress += (float)size/total;
        progressBlock(upProgress);
    }];
    
    [request setCompletionBlock:^{
        upProgress=0;
        NSError *errorForJSON = [NSError errorWithDomain:@"请求数据解析为json格式,发出错误" code:2014 userInfo:@{@"请求数据json解析错误": @"中文",@"serial the data to json error":@"English"}];
        id jsonData = [NSJSONSerialization JSONObjectWithData:[request responseData] options:0 error:&errorForJSON];
        completedBlock(jsonData,[request responseString]);
    }];
    
    [request setFailedBlock:^{
        failed([request error]);
    }];
    
    [request startAsynchronous];
    
    kNSLog(@"ASIClient 文件上传:%@ size=%.2f MB  key=%@",path,fData.length/1024.0/1024.0,dataKey);
    kNSLog(@"ASIClient 文件上传參数:%@",params);
    
    return request;
}


+ (ASIHTTPRequest *)ResumeDown_Path:(NSString *)path writeTo:(NSString *)destinationPath tempPath:(NSString *)tempPath fileName:(NSString *)name setProgress:(KKProgressBlock )progressBlock completed:(ASIBasicBlock )completedBlock failed:(KKFailedBlock )failed
{
    __weak ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:path]];
    NSString *filePath = nil;
    if ([destinationPath hasSuffix:@"/"]) {
        filePath = [NSString stringWithFormat:@"%@%@",destinationPath,name];
    }
    else
    {
        filePath = [NSString stringWithFormat:@"%@/%@",destinationPath,name];
    }
    
    [request setDownloadDestinationPath:filePath];
    
    NSString *tempForDownPath = nil;
    if ([tempPath hasSuffix:@"/"]) {
        tempForDownPath = [NSString stringWithFormat:@"%@%@.download",tempPath,name];
    }
    else
    {
        tempForDownPath = [NSString stringWithFormat:@"%@/%@.download",tempPath,name];
    }
    
    [request setTemporaryFileDownloadPath:tempForDownPath];
    [request setAllowResumeForFileDownloads:YES];
    
    __block float downProgress = 0;
    downProgress = [[NSUserDefaults standardUserDefaults] floatForKey:@"ASIClient_ResumeDOWN_PROGRESS"];
    [request setBytesReceivedBlock:^(unsigned long long size, unsigned long long total) {
        downProgress += (float)size/total;
        if (downProgress >1.0) {
            downProgress=1.0;
        }
        [[NSUserDefaults standardUserDefaults] setFloat:downProgress forKey:@"ASIClient_ResumeDOWN_PROGRESS"];
        progressBlock(downProgress);
    }];
    
    [request setCompletionBlock:^{
        downProgress = 0;
        [[NSUserDefaults standardUserDefaults] setFloat:downProgress forKey:@"ASIClient_ResumeDOWN_PROGRESS"];
        completedBlock();
        if ([[NSFileManager defaultManager] fileExistsAtPath:tempForDownPath]) {
            //NSError *errorForDelete = [NSError errorWithDomain:@"删除暂时文件错误发生!" code:2015 userInfo:@{@"删除暂时文件错误发生": @"中文",@"delete the temp fife error":@"English"}];
            //[[NSFileManager defaultManager] removeItemAtPath:tempForDownPath error:&errorForDelete];
            kNSLog(@"l  %d> %s",__LINE__,__func__);
        }
    }];
    
    [request setFailedBlock:^{
        failed([request error]);
    }];
    
    [request startAsynchronous];
    
    kNSLog(@"ASIClient 下载文件:%@ ",path);
    kNSLog(@"ASIClient 保存路径:%@",filePath);
    if (downProgress >0 && downProgress) {
        if (downProgress >=1.0) downProgress = 0.9999;
        kNSLog(@"ASIClient 上次下载已完毕:%.2f/100",downProgress*100);
    }
    return request;
}
@end


在使用这个时候。注意NSJSONSerialization的options參数。

【推广】 免费学中医,健康全家人
原文地址:https://www.cnblogs.com/ldxsuanfa/p/10683743.html