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 封装相关推荐
- ios html5上架,IOS免签封装,完美解决H5应用上架App Store受阻的尴尬
通过H5封装成IOS的应用在初期的确受到了广大开发者们的追捧,因为只需要有H5网站就可以通过WEBAPP框架在几分钟内生成一个IOS的APP应用,几乎不需要什么成本.而对于普通玩家来说,在一些专业IO ...
- IOS免签封装,解决H5应用上架App Store被拒的问题
通过H5封装成IOS的应用在初期的确受到了广大开发者们的追捧,因为只需要有H5网站就可以通过WEBAPP框架在几分钟内生成一个IOS的APP应用,几乎不需要什么成本.而对于普通玩家来说,在一些专业IO ...
- iOS ASIHTTPRequest用https协议加密请求
iOS 终端请求服务端数据时,为了保证数据安全,我们一般会使用https协议加密,而对于iOS的网络编程,我们一般会使用开源框架:ASIHTTPRequest,但是如果使用传统的http方式,即使忽略 ...
- iOS (封装)一句话调用系统的alertView和alertController
前言: 本文仅作参考存留,请用新版封装:iOS 更加优雅便捷的UIAlertView/UIAlertController封装使用 UIAlertController是iOS8.0之后出来的新方法,其将 ...
- iOS 自己封装的SDK 打包与合并,新手教程!!!
前言 (1)这个时候就得说下静态库,动态库区别. 静态库:1.模块化,分工合作.2.避免少量改动经常导致大量的重复编译链接.3.也可以重用,注意不是共享使用. ...
- ASIHttpRequest封装
ASIHttpRequest是一个非常好的库,只是直接使用稍嫌麻烦,以下就尝试来封装一下吧. 思路:每次请求时,须要创建一个ASIHttpRequest对象,设置它的属性(url,delegate.p ...
- 基于iOS 10封装的下载器(支持存储读取、断点续传、后台下载、杀死APP重启后的断点续传等功能)
原文 资源来自:http://www.cocoachina.com/ios/20170316/18901.html 概要 在决定自己封装一个下载器前,我本以为没有那么复杂,可在实际开发过程中困难重重, ...
- ios免签封装去网址,隐藏状态栏,不显示顶部网址。
由于IOS封装原生ipa文件需要企业签名,基本上都是忽悠.因为共享的几天就掉,独享的又贵,TF更是贵得惊人,所以就有了ios免签一说. 网站封装会出现3个坑,前面2个坑教程很多,今天主要解决大坑,全网 ...
- iOS 自定义封装WKWebView,可以网页回退转跳,与网页交互事件监听,解决内存释放问题
自己封装的WKWebView,功能如下: 1.加载网页URL 2.网页转跳返回 3.与网页之间的交互事件 4.退出界面清除缓存 5.释放内存,防止内存溢出 使用方法: HBWebViewVC *vc ...
最新文章
- 批量从apk文件中提取出so文件
- 8.1-8.5 shell介绍,命令历史,命令补全和别名,通配符,输入输出重定向
- 01Spring的helloworld程序
- 舞伴配对问题java_舞伴配对问题
- idea测试单元错误_不要单元测试错误
- css中的段落控制 【 text-indent】
- AcWing进阶算法课Level-4 第六章 搜索 (模拟退火,爬山)
- HCIP-loT——关键特性
- matlab图像拼接 设计,MATLAB图像拼接算法及实现.doc
- isodata算法确定k均值聚类的k值
- VisualBasic程序设计第二章的学习与自测
- 万字长文带你快速了解并上手Testcontainers
- Vue + TypeScript + Element 搭建简洁时尚的博客网站及踩坑记
- github下载文件时让输入用户名和密码
- 关于学术文献推荐系统的调研报告
- ElasticSearch入门:ES分词器与自定义分词器
- 关于“卷积”的通俗解释
- onlyoffice 源码编译,破解20连接数限制,并部署到centos7
- ipad投屏到linux
- 【FCPX】Final Cut ProX 入门必备快捷键/插件下载链接/常用字体转场特效
热门文章
- JavaScript基础一
- JQuery窗口拖动效果
- Android layout_gravity
- SSDT – Error SQL70001 This statement is not recognized in this context-摘自网络
- linux下makefile使用
- 快速配置Windows 2003平台下实现 IIS(WEB)站点的安全(SSL加密技术!)
- 『树上匹配 树形dp』
- Quartus调用Modelsim SE避免重复编译Altera器件库的方法
- c#读取xml文件配置文件Winform及WebForm-Demo具体解释
- forward 和redirect的区别