博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
iOS ASIHttpRequest 封装
阅读量:6069 次
发布时间:2019-06-20

本文共 17932 字,大约阅读时间需要 59 分钟。

ASIHttpRequest 封装

////  HttpUtil.h//  AshineDoctor////  Created by zhangqipu on 15/2/6.//  Copyright (c) 2015年 esuizhen. All rights reserved.////  功能 :网络请求下载////  描述 :POST请求、文件下载、文件上传//#import 
#import "ASIHTTPRequest.h"#import "ASIFormDataRequest.h"#import "ASINetworkQueue.h"#import "Common.h"/** * 请求完成回调块声明 */typedef void (^CompleteBlock)(id responseData);typedef void (^QueueCompleteBlock)(ASINetworkQueue *);@interface HttpUtil : NSObject
/** * 网络工具单例 * * @return return value description */+ (HttpUtil *)sharedHttpUtil;/** * 获取登陆认证Token * * @param path 后台请求接口 * @param paramDic 请求参数 */+ (void)authenticateWithPath:(NSString *)path params:(NSDictionary *)paramDic completed:(CompleteBlock)completeBlock;/** * GET请求 * * @param path 后台接口 * @param paramDic 请求参数字典 * @param completeBlock 请求完成回调块 * @param isShow 是否显示等待提示框 * * @return return value description */+ (ASIHTTPRequest *)getRequestWithPath:(NSString *)path params:(NSDictionary *)paramDic showHud:(BOOL)isShow completed:(CompleteBlock)completeBlock;/** * POST请求 * * @param path 后台接口 * @param paramDic 请求参数字典 * @param completeBlock 请求完成回调块 * * @return return value description */+ (ASIHTTPRequest *)postRequestWithPath:(NSString *)path params:(NSDictionary *)paramDic showHud:(BOOL)isShow completed:(CompleteBlock)completeBlock;+ (ASIHTTPRequest *)postJsonWithPath:(NSString *)path params:(NSDictionary *)paramDic showHud:(BOOL)isShow completed:(CompleteBlock)completeBlock;+ (ASIHTTPRequest *)putRequestWithPath:(NSString *)path params:(NSDictionary *)paramDic showHud:(BOOL)isShow completed:(CompleteBlock)completeBlock;+ (ASIHTTPRequest *)deleteRequestWithPath:(NSString *)path params:(NSDictionary *)paramDic showHud:(BOOL)isShow completed:(CompleteBlock)completeBlock;/** * 文件上传 * * @param path 后台接口 * @param filePath 上传文件路径 * @param fileKey 上传文件对应服务器端Key值 * @param paramDic 请求参数字典 * @param completeBlock 请求完成回调 * * @return return value description */+ (ASIHTTPRequest *)uploadFileWithPath:(NSString *)path filePath:(NSString *)filePath fileKey:(NSString *)fileKey paramDic:(NSDictionary *)paramDic showHud:(BOOL)isShow completed:(CompleteBlock)completeBlock;+ (ASIHTTPRequest *)uploadFileWithPath:(NSString *)path filePath:(NSString *)filePath fileKey:(NSString *)fileKey paramDic:(NSDictionary *)paramDic showHud:(BOOL)isShow progressDelegate:(id
)progressDelgate completed:(CompleteBlock)completeBlock;/** * 多文件上传 * * @param path 后台接口 * @param filePaths 上传文件的所有路径 * @param fileKey 上传文件对应服务器端Key值 * @param paramDic 请求参数字典 * @param completeBlock 每个文件上传完成的回调 * @param queueComplete 所有文件上传完成的回调 * * @return <#return value description#> */+ (ASINetworkQueue *)uploadFilesWithPath:(NSString *)path filePaths:(NSArray *)filePaths fileKey:(NSString *)fileKey paramDic:(NSDictionary *)paramDic showHud:(BOOL)isShow completed:(CompleteBlock)completeBlock queueCmoplete:(QueueCompleteBlock)queueComplete;/** * 文件下载 * * @param path 后台接口 * @param destinationPath 下载文件目的地 * @param completeBlock 请求完成回调 * * @return return value description */+(ASIHTTPRequest *)downloadFileWithPath:(NSString *)path destinationPath:(NSString *)destinationPath completed:(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 *)path params:(NSDictionary *)paramDic completed:(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 *)path params:(NSDictionary *)paramDic showHud:(BOOL)isShow completed:(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:anotherRequest andUrl:urlStr andPrams:paramDic dismissHud:isShow andCompleteBlock:completeBlock]; }]; [request setFailedBlock:^{ [self failedActionWithRequest:anotherRequest andCompleteBlock:completeBlock]; }]; request.delegate = self; [request startAsynchronous]; return request;}#pragma mark -#pragma mark POST请求+ (ASIHTTPRequest *)requestWithPath:(NSString *)path method:(NSString *)method params:(NSDictionary *)paramDic showHud:(BOOL)isShow completed:(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:anotherRequest andUrl:urlStr andPrams:paramDic dismissHud:isShow andCompleteBlock:completeBlock]; }]; [request setFailedBlock:^{ [self failedActionWithRequest:anotherRequest andCompleteBlock:completeBlock]; }]; [request startAsynchronous]; return request;}+ (ASIHTTPRequest *)postRequestWithPath:(NSString *)path params:(NSDictionary *)paramDic showHud:(BOOL)isShow completed:(CompleteBlock)completeBlock{ return [self requestWithPath:path method:@"POST" params:paramDic showHud:isShow completed:completeBlock];}+ (ASIHTTPRequest *)postJsonWithPath:(NSString *)path params:(NSDictionary *)paramDic showHud:(BOOL)isShow completed:(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:anotherRequest andUrl:urlStr andPrams:paramDic dismissHud:isShow andCompleteBlock:completeBlock]; }]; [request setFailedBlock:^{ [self failedActionWithRequest:anotherRequest andCompleteBlock:completeBlock]; }]; [request startAsynchronous]; return request;}+ (ASIHTTPRequest *)putRequestWithPath:(NSString *)path params:(NSDictionary *)paramDic showHud:(BOOL)isShow completed:(CompleteBlock)completeBlock{ return [self requestWithPath:path method:@"PUT" params:paramDic showHud:isShow completed:completeBlock];}+ (ASIHTTPRequest *)deleteRequestWithPath:(NSString *)path params:(NSDictionary *)paramDic showHud:(BOOL)isShow completed:(CompleteBlock)completeBlock{ return [self requestWithPath:path method:@"DELETE" params:paramDic showHud:isShow completed:completeBlock];}#pragma mark -#pragma mark 上传文件+ (ASIHTTPRequest *)uploadFileWithPath:(NSString *)path filePath:(NSString *)filePath fileKey:(NSString *)fileKey paramDic:(NSDictionary *)paramDic showHud:(BOOL)isShow completed:(CompleteBlock)completeBlock{ return [self uploadFileWithPath:path filePath:filePath fileKey:fileKey paramDic:paramDic showHud:isShow progressDelegate:nil completed:completeBlock];}+ (ASIHTTPRequest *)uploadFileWithPath:(NSString *)path filePath:(NSString *)filePath fileKey:(NSString *)fileKey paramDic:(NSDictionary *)paramDic showHud:(BOOL)isShow progressDelegate:(id
)progressDelgate completed:(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:anotherRequest andUrl:nil andPrams:nil dismissHud:isShow andCompleteBlock: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 *)path filePaths:(NSArray *)filePaths fileKey:(NSString *)fileKey paramDic:(NSDictionary *)paramDic showHud:(BOOL)isShow completed:(CompleteBlock)completeBlock queueCmoplete:(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:anotherRequest andUrl:nil andPrams:nil dismissHud:isShow andCompleteBlock: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 *)path destinationPath:(NSString *)destinationPath completed:(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 *)anotherRequest andUrl:nil andPrams:nil dismissHud:NO andCompleteBlock:completeBlock]; }]; [request setFailedBlock:^{ [self failedActionWithRequest:(ASIFormDataRequest *)anotherRequest andCompleteBlock:completeBlock]; }]; [request startAsynchronous]; return request;}#pragma mark -#pragma mark 请求完成动作+ (void)completeActionWithRequest:(ASIFormDataRequest *)request andUrl:(NSString *)urlStr andPrams:(NSDictionary *)paramDic dismissHud:(BOOL)isDismiss andCompleteBlock:(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 *)request andCompleteBlock:(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

你可能感兴趣的文章
ylbtech-LanguageSamples-PartialTypes(部分类型)
查看>>
福建省促进大数据发展:变分散式管理为统筹集中式管理
查看>>
开发环境、生产环境、测试环境的基本理解和区别
查看>>
tomcat多应用之间如何共享jar
查看>>
Flex前后台交互,service层调用后台服务的简单封装
查看>>
技术汇之物联网设备网关技术架构设计
查看>>
OSX10.11 CocoaPods 升级总结
查看>>
深入浅出Netty
查看>>
3.使用maven创建java web项目
查看>>
笔记本搜索不到某一AP广播的SSID,信道的原因
查看>>
基于Spring MVC的异常处理及日志管理
查看>>
MediaBrowserService 音乐播放项目《IT蓝豹》
查看>>
MySQL入门12-数据类型
查看>>
Windows Azure 保留已存在的虚拟网络外网IP(云服务)
查看>>
修改字符集
查看>>
HackTheGame 攻略 - 第四关
查看>>
js删除数组元素
查看>>
带空格文件名的处理(find xargs grep ..etc)
查看>>
华为Access、Hybrid和Trunk的区别和设置
查看>>
centos使用docker下安装mysql并配置、nginx
查看>>