iOS ASIHttpRequest 封装
生活随笔
收集整理的這篇文章主要介紹了
iOS ASIHttpRequest 封装
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
ASIHttpRequest 封裝
// // HttpUtil.h // AshineDoctor // // Created by zhangqipu on 15/2/6. // Copyright (c) 2015年 esuizhen. All rights reserved. // // 功能 :網絡請求下載 // // 描述 :POST請求、文件下載、文件上傳 //#import <Foundation/Foundation.h> #import "ASIHTTPRequest.h" #import "ASIFormDataRequest.h" #import "ASINetworkQueue.h"#import "Common.h"/*** 請求完成回調塊聲明*/ typedef void (^CompleteBlock)(id responseData); typedef void (^QueueCompleteBlock)(ASINetworkQueue *);@interface HttpUtil : NSObject <ASIProgressDelegate>/*** 網絡工具單例** @return return value description*/ + (HttpUtil *)sharedHttpUtil;/*** 獲取登陸認證Token** @param path 后臺請求接口* @param paramDic 請求參數*/ + (void)authenticateWithPath:(NSString *)pathparams:(NSDictionary *)paramDiccompleted:(CompleteBlock)completeBlock;/*** GET請求** @param path 后臺接口* @param paramDic 請求參數字典* @param completeBlock 請求完成回調塊* @param isShow 是否顯示等待提示框** @return return value description*/ + (ASIHTTPRequest *)getRequestWithPath:(NSString *)pathparams:(NSDictionary *)paramDicshowHud:(BOOL)isShowcompleted:(CompleteBlock)completeBlock;/*** POST請求** @param path 后臺接口* @param paramDic 請求參數字典* @param completeBlock 請求完成回調塊** @return return value description*/ + (ASIHTTPRequest *)postRequestWithPath:(NSString *)pathparams:(NSDictionary *)paramDicshowHud:(BOOL)isShowcompleted:(CompleteBlock)completeBlock;+ (ASIHTTPRequest *)postJsonWithPath:(NSString *)pathparams:(NSDictionary *)paramDicshowHud:(BOOL)isShowcompleted:(CompleteBlock)completeBlock;+ (ASIHTTPRequest *)putRequestWithPath:(NSString *)pathparams:(NSDictionary *)paramDicshowHud:(BOOL)isShowcompleted:(CompleteBlock)completeBlock;+ (ASIHTTPRequest *)deleteRequestWithPath:(NSString *)pathparams:(NSDictionary *)paramDicshowHud:(BOOL)isShowcompleted:(CompleteBlock)completeBlock;/*** 文件上傳** @param path 后臺接口* @param filePath 上傳文件路徑* @param fileKey 上傳文件對應服務器端Key值* @param paramDic 請求參數字典* @param completeBlock 請求完成回調** @return return value description*/ + (ASIHTTPRequest *)uploadFileWithPath:(NSString *)pathfilePath:(NSString *)filePathfileKey:(NSString *)fileKeyparamDic:(NSDictionary *)paramDicshowHud:(BOOL)isShowcompleted:(CompleteBlock)completeBlock;+ (ASIHTTPRequest *)uploadFileWithPath:(NSString *)pathfilePath:(NSString *)filePathfileKey:(NSString *)fileKeyparamDic:(NSDictionary *)paramDicshowHud:(BOOL)isShowprogressDelegate:(id <ASIProgressDelegate>)progressDelgatecompleted:(CompleteBlock)completeBlock;/*** 多文件上傳** @param path 后臺接口* @param filePaths 上傳文件的所有路徑* @param fileKey 上傳文件對應服務器端Key值* @param paramDic 請求參數字典* @param completeBlock 每個文件上傳完成的回調* @param queueComplete 所有文件上傳完成的回調** @return <#return value description#>*/ + (ASINetworkQueue *)uploadFilesWithPath:(NSString *)pathfilePaths:(NSArray *)filePathsfileKey:(NSString *)fileKeyparamDic:(NSDictionary *)paramDicshowHud:(BOOL)isShowcompleted:(CompleteBlock)completeBlockqueueCmoplete:(QueueCompleteBlock)queueComplete;/*** 文件下載** @param path 后臺接口* @param destinationPath 下載文件目的地* @param completeBlock 請求完成回調** @return return value description*/ +(ASIHTTPRequest *)downloadFileWithPath:(NSString *)pathdestinationPath:(NSString *)destinationPathcompleted:(CompleteBlock)completeBlock;@end// // HttpUtil.m // AshineDoctor // // Created by JiangYue on 15/2/6. // Copyright (c) 2015年 esuizhen. All rights reserved. //#import "HttpUtil.h"@implementation HttpUtil#pragma mark - #pragma mark 網絡工具單例static UIProgressView *progressView;+ (HttpUtil *)sharedHttpUtil {static HttpUtil *httpUtil = nil;static dispatch_once_t onceToken;dispatch_once(&onceToken, ^{httpUtil = [[self alloc] init];});return httpUtil; }#pragma mark - #pragma mark 登陸請求+ (void)authenticateWithPath:(NSString *)pathparams:(NSDictionary *)paramDiccompleted:(CompleteBlock)completeBlock {NSString *urlStr = [NSString stringWithFormat:@"%@%@", BASE_URL, path];NSURL *url = [NSURL URLWithString:urlStr];ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];ASIFormDataRequest *anotherRequest = request;// 設置請求參數[paramDic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {[request setPostValue:obj forKey:key];}];[request addRequestHeader:@"Authorization" value:@"Basic YmFwbHVvX2FwaWtleTpiMjEwOTUzMDFmYzM1MzFm"];request.shouldAttemptPersistentConnection = NO;[request setCompletionBlock:^{NSDictionary *responseDic =[NSJSONSerialization JSONObjectWithData:anotherRequest.responseData options:NSJSONReadingMutableContainers error:nil];completeBlock(responseDic);}];[request setFailedBlock:^{ShowHudWithMessage(@"認證失敗!");completeBlock(nil);NSLog(@"%@", anotherRequest.error);}];[request startAsynchronous]; }#pragma mark - #pragma mark GET請求+ (ASIHTTPRequest *)getRequestWithPath:(NSString *)pathparams:(NSDictionary *)paramDicshowHud:(BOOL)isShowcompleted:(CompleteBlock)completeBlock {NSMutableString *urlStr = [NSMutableString stringWithFormat:@"%@%@?", BASE_URL, path];[paramDic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {[urlStr appendFormat:@"%@=%@&", key, obj];}];ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlStr]];ASIFormDataRequest *anotherRequest = request;NSString *token = StandardUserDefautsGet(kToken);if (token) [request addRequestHeader:@"Authorization" value:token];request.requestMethod = @"GET";request.shouldAttemptPersistentConnection = NO;[request setCompletionBlock:^{[self completeActionWithRequest:anotherRequestandUrl:urlStrandPrams:paramDicdismissHud:isShowandCompleteBlock:completeBlock];}];[request setFailedBlock:^{[self failedActionWithRequest:anotherRequest andCompleteBlock:completeBlock];}];request.delegate = self;[request startAsynchronous];return request; }#pragma mark - #pragma mark POST請求+ (ASIHTTPRequest *)requestWithPath:(NSString *)pathmethod:(NSString *)methodparams:(NSDictionary *)paramDicshowHud:(BOOL)isShowcompleted:(CompleteBlock)completeBlock {NSString *urlStr = [NSString stringWithFormat:@"%@%@", BASE_URL, path];NSURL *url = [NSURL URLWithString:urlStr];ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];ASIFormDataRequest *anotherRequest = request;request.requestMethod = method;// 設置請求參數[paramDic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {[request setPostValue:obj forKey:key];}];NSString *token = StandardUserDefautsGet(kToken);if (token) [request addRequestHeader:@"Authorization" value:token];request.shouldAttemptPersistentConnection = NO;[request setCompletionBlock:^{[self completeActionWithRequest:anotherRequestandUrl:urlStrandPrams:paramDicdismissHud:isShowandCompleteBlock:completeBlock];}];[request setFailedBlock:^{[self failedActionWithRequest:anotherRequest andCompleteBlock:completeBlock];}];[request startAsynchronous];return request; }+ (ASIHTTPRequest *)postRequestWithPath:(NSString *)pathparams:(NSDictionary *)paramDicshowHud:(BOOL)isShowcompleted:(CompleteBlock)completeBlock {return [self requestWithPath:path method:@"POST" params:paramDic showHud:isShow completed:completeBlock]; }+ (ASIHTTPRequest *)postJsonWithPath:(NSString *)pathparams:(NSDictionary *)paramDicshowHud:(BOOL)isShowcompleted:(CompleteBlock)completeBlock {NSString *urlStr = [NSString stringWithFormat:@"%@%@", BASE_URL, path];NSURL *url = [NSURL URLWithString:urlStr];ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];ASIFormDataRequest *anotherRequest = request;// 設置請求參數NSData *postData = [ToolsNSObject jsonFromDictionary:paramDic];NSString *token = StandardUserDefautsGet(kToken);if (token) [request addRequestHeader:@"Authorization" value:token];[request addRequestHeader:@"Content-type" value:@"application/json"];[request setPostBody:[NSMutableData dataWithData:postData]];request.shouldAttemptPersistentConnection = NO;[request setCompletionBlock:^{[self completeActionWithRequest:anotherRequestandUrl:urlStrandPrams:paramDicdismissHud:isShowandCompleteBlock:completeBlock];}];[request setFailedBlock:^{[self failedActionWithRequest:anotherRequest andCompleteBlock:completeBlock];}];[request startAsynchronous];return request; }+ (ASIHTTPRequest *)putRequestWithPath:(NSString *)pathparams:(NSDictionary *)paramDicshowHud:(BOOL)isShowcompleted:(CompleteBlock)completeBlock {return [self requestWithPath:path method:@"PUT" params:paramDic showHud:isShow completed:completeBlock]; }+ (ASIHTTPRequest *)deleteRequestWithPath:(NSString *)pathparams:(NSDictionary *)paramDicshowHud:(BOOL)isShowcompleted:(CompleteBlock)completeBlock {return [self requestWithPath:path method:@"DELETE" params:paramDic showHud:isShow completed:completeBlock]; }#pragma mark - #pragma mark 上傳文件+ (ASIHTTPRequest *)uploadFileWithPath:(NSString *)pathfilePath:(NSString *)filePathfileKey:(NSString *)fileKeyparamDic:(NSDictionary *)paramDicshowHud:(BOOL)isShowcompleted:(CompleteBlock)completeBlock {return [self uploadFileWithPath:path filePath:filePath fileKey:fileKey paramDic:paramDic showHud:isShow progressDelegate:nil completed:completeBlock]; }+ (ASIHTTPRequest *)uploadFileWithPath:(NSString *)pathfilePath:(NSString *)filePathfileKey:(NSString *)fileKeyparamDic:(NSDictionary *)paramDicshowHud:(BOOL)isShowprogressDelegate:(id <ASIProgressDelegate>)progressDelgatecompleted:(CompleteBlock)completeBlock {NSString *urlStr = [NSString stringWithFormat:@"%@%@", BASE_URL, path];NSURL *url = [NSURL URLWithString:urlStr];ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];ASIFormDataRequest *anotherRequest = request;// 設置請求參數[paramDic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {[request setPostValue:obj forKey:key];}];NSString *token = StandardUserDefautsGet(kToken);if (token) [request addRequestHeader:@"Authorization" value:token];// 設置上傳文件和服務器鍵值[request setFile:filePath forKey:fileKey];[request setCompletionBlock:^{[self completeActionWithRequest:anotherRequestandUrl:nilandPrams:nildismissHud:isShowandCompleteBlock:completeBlock];}];[request setFailedBlock:^{[self failedActionWithRequest:anotherRequest andCompleteBlock:completeBlock];}];[request setTimeOutSeconds:100];if (progressDelgate) {[request setShowAccurateProgress:YES];[request setUploadProgressDelegate:progressDelgate];}[request startAsynchronous];return request; }+ (ASINetworkQueue *)uploadFilesWithPath:(NSString *)pathfilePaths:(NSArray *)filePathsfileKey:(NSString *)fileKeyparamDic:(NSDictionary *)paramDicshowHud:(BOOL)isShowcompleted:(CompleteBlock)completeBlockqueueCmoplete:(QueueCompleteBlock)queueComplete {ASINetworkQueue *queue = [ASINetworkQueue queue];[queue setDelegate:self];for (NSUInteger i = 0; i < filePaths.count; i++) {NSString *urlStr = [NSString stringWithFormat:@"%@%@", BASE_URL, path];NSURL *url = [NSURL URLWithString:urlStr];ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];ASIFormDataRequest *anotherRequest = request;NSString *token = StandardUserDefautsGet(kToken);if (token) [request addRequestHeader:@"Authorization" value:token];// 設置上傳文件和服務器鍵值[request setFile:filePaths[i] forKey:fileKey];[request setCompletionBlock:^{[self completeActionWithRequest:anotherRequestandUrl:nilandPrams:nildismissHud:isShowandCompleteBlock:completeBlock];}];[request setFailedBlock:^{[self failedActionWithRequest:anotherRequest andCompleteBlock:completeBlock];}];[queue addOperation:request];}[queue setQueueDidFinishBlock:queueComplete];[queue go];return queue; }#pragma mark - #pragma mark 下載文件+ (ASIHTTPRequest *)downloadFileWithPath:(NSString *)pathdestinationPath:(NSString *)destinationPathcompleted:(CompleteBlock)completeBlock {NSString *urlStr = [NSString stringWithFormat:@"%@", path];NSURL *url = [NSURL URLWithString:urlStr];ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];ASIHTTPRequest *anotherRequest = request;// 設置下載文件路徑[request setDownloadDestinationPath:destinationPath];[request setCompletionBlock:^{[self completeActionWithRequest:(ASIFormDataRequest *)anotherRequestandUrl:nilandPrams:nildismissHud:NOandCompleteBlock:completeBlock];}];[request setFailedBlock:^{[self failedActionWithRequest:(ASIFormDataRequest *)anotherRequest andCompleteBlock:completeBlock];}];[request startAsynchronous];return request; }#pragma mark - #pragma mark 請求完成動作+ (void)completeActionWithRequest:(ASIFormDataRequest *)requestandUrl:(NSString *)urlStrandPrams:(NSDictionary *)paramDicdismissHud:(BOOL)isDismissandCompleteBlock:(CompleteBlock)completeBlock {NSError *err = nil;id jsonData = nil;if (request.responseData){NSString *jsonStr =[[NSString alloc] initWithBytes:[request.responseData bytes]length:[request.responseData length]encoding:NSUTF8StringEncoding];if ([jsonStr isEqualToString:@""]) {if (request.responseStatusCode == 200) {jsonStr = @"{\"code\":\"200\", \"message\":\"success\"}";} else {return ;}}jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\n"withString:@""];PRETTY_LOG(([NSString stringWithFormat:@"[ API ] %@\n[ Reponse Json ] \n%@", [request.url absoluteString], jsonStr]));NSData *data = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];if (data) {jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];}}completeBlock(jsonData); }#pragma mark - #pragma mark 請求失敗動作+ (void)failedActionWithRequest:(ASIFormDataRequest *)requestandCompleteBlock:(CompleteBlock)completeBlock {PRETTY_LOG(request.error);//ShowTopTips(@"", @"網絡狀況不好,請稍候再試!", @"heart");completeBlock(nil);}+ (void)setProgress:(float)newProgress {PRETTY_LOG(([NSString stringWithFormat:@"%f", newProgress])); }@end轉載于:https://www.cnblogs.com/zhangqipu/p/5170552.html
總結
以上是生活随笔為你收集整理的iOS ASIHttpRequest 封装的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Ibatis学习总结7--SqlMapC
- 下一篇: HDU-2612 Find a way