對ASIHTTPRequest的封裝,asihttprequest封裝
.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(...)#endifextern 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 上傳檔案對應伺服器接收的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對應伺服器接收的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參數。
使用CFNetWork怎實現上傳
樓主看看ASIHTTPRequest的實現原理。ASIHTTPRequest封裝了CFNetwork API。當然ASIHTTPRequest是支援上傳下載的。 查看原帖>>
問ASIHTTPRequest中有什功可以?
給你看看這段例子代碼:NSURL *url = [NSURL URLWithString:@" www.baidu.com"];ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];[request start];NSError *error = [request error];if (!error) { NSString *response = [request responseString];}