HttpTool.h

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h> typedef void(^HttpSuccessBlock)(id json);
typedef void(^HttpFailureBlock)(NSError *error);
typedef void(^HttpDownloadProgressBlock)(CGFloat progress);
typedef void(^HttpUploadProgressBlock)(CGFloat progress); @interface HttpTool : NSObject /**
get网络请求 @param path url地址
@param params url参数 NSDictionary类型
@param success 请求成功 返回NSDictionary或NSArray
@param failure 请求失败 返回NSError
*/
+ (void)getWithPath:(NSString *)path
params:(NSDictionary *)params
success:(HttpSuccessBlock)success
failure:(HttpFailureBlock)failure; /**
post网络请求 @param path url地址
@param params url参数 NSDictionary类型
@param success 请求成功 返回NSDictionary或NSArray
@param failure 请求失败 返回NSError
*/
+ (void)postWithPath:(NSString *)path
params:(NSDictionary *)params
success:(HttpSuccessBlock)success
failure:(HttpFailureBlock)failure; /**
下载文件 @param path url路径
@param success 下载成功
@param failure 下载失败
@param progress 下载进度
*/
+ (void)downloadWithPath:(NSString *)path
success:(HttpSuccessBlock)success
failure:(HttpFailureBlock)failure
progress:(HttpDownloadProgressBlock)progress; /**
上传图片 @param path url地址
@param image UIImage对象
@param thumbName imagekey
@param params 上传参数
@param success 上传成功
@param failure 上传失败
@param progress 上传进度
*/
+ (void)uploadImageWithPath:(NSString *)path
params:(NSDictionary *)params
thumbName:(NSString *)thumbName
image:(UIImage *)image
success:(HttpSuccessBlock)success
failure:(HttpFailureBlock)failure
progress:(HttpUploadProgressBlock)progress; @end

HttpTool.m

#import "HttpTool.h"
#import "AFNetworking/AFNetworking.h" static NSString *kBaseUrl = SERVER_HOST; @interface AFHttpClient : AFHTTPSessionManager + (instancetype)sharedClient; @end @implementation AFHttpClient + (instancetype)sharedClient { static AFHttpClient *client = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{ NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; client = [[AFHttpClient alloc] initWithBaseURL:[NSURL URLWithString:kBaseUrl] sessionConfiguration:configuration];
// 接收参数类型
client.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/plain", @"text/gif", nil];
// 设置超时时间,默认60
client.requestSerializer.timeoutInterval = ;
// 安全策略
client.securityPolicy = [AFSecurityPolicy defaultPolicy];
}); return client;
} @end @implementation HttpTool + (void)getWithPath:(NSString *)path params:(NSDictionary *)params success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure { // 获取完整的url路径
NSString *url = [kBaseUrl stringByAppendingPathComponent:path]; [[AFHttpClient sharedClient] GET:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { success(responseObject); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { failure(error); }];
} + (void)postWithPath:(NSString *)path params:(NSDictionary *)params success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure { // 获取完整的url路径
NSString *url = [kBaseUrl stringByAppendingPathComponent:path]; [[AFHttpClient sharedClient] POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { success(responseObject); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { failure(error); }];
} + (void)downloadWithPath:(NSString *)path success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure progress:(HttpDownloadProgressBlock)progress { // 获取完整的url路径
NSString *url = [kBaseUrl stringByAppendingPathComponent:path]; // 下载
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]]; NSURLSessionDownloadTask *downloadTask = [[AFHttpClient sharedClient] downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) { progress(downloadProgress.fractionCompleted); } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) { // 获取沙盒cache路径
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil]; return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]]; } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) { if (error) {
failure(error);
} else {
success(filePath.path);
} }]; [downloadTask resume];
} + (void)uploadImageWithPath:(NSString *)path params:(NSDictionary *)params thumbName:(NSString *)thumbName image:(UIImage *)image success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure progress:(HttpUploadProgressBlock)progress { // 获取完整的url路径
NSString *url = [kBaseUrl stringByAppendingPathComponent:path]; NSData *data = UIImagePNGRepresentation(image); [[AFHttpClient sharedClient] POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) { [formData appendPartWithFileData:data name:thumbName fileName:@"01.png" mimeType:@"image/png"]; } progress:^(NSProgress * _Nonnull uploadProgress) { progress(uploadProgress.fractionCompleted); } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { success(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { failure(error);
}];
} @end

对AFNetworking的二次封装的更多相关文章

  1. AFNetworking二次封装的那些事

    AFNetworking可是iOS网络开发的神器,大大简便了操作.不过网络可是重中之重,不能只会用AFNetworking.我觉得网络开发首先要懂基本的理论,例如tcp/ip,http协议,之后要了解 ...

  2. iOS项目相关@AFN&SDWeb的二次封装

    一,AFNetworking跟SDWebImge是功能强大且常用的第三方,然而在实际应用中需要封装用来复用今天就跟大家分享一下AFN&SDWeb的二次封装 1. HttpClient.h及.m ...

  3. iOS菜鸟之AFN的二次封装

    我用一个单例类将一些常用的网络请求进行了二次封装,主要包括post请求 get请求  图片文件上传下载  视频的断点续传等功能. 首先大家先去github上下载AFN,将文件夹内的AFNetworki ...

  4. 对百度WebUploader开源上传控件的二次封装,精简前端代码(两句代码搞定上传)

    前言 首先声明一下,我这个是对WebUploader开源上传控件的二次封装,底层还是WebUploader实现的,只是为了更简洁的使用他而已. 下面先介绍一下WebUploader 简介: WebUp ...

  5. Quick Cocos (2.2.5plus)CoinFlip解析(MenuScene display AdBar二次封装)

    转载自:http://cn.cocos2d-x.org/tutorial/show?id=1621 从Samples中找到CoinFlip文件夹,复制其中的 res 和 script 文件夹覆盖新建工 ...

  6. 对jquery的ajax进行二次封装以及ajax缓存代理组件:AjaxCache

    虽然jquery的较新的api已经很好用了, 但是在实际工作还是有做二次封装的必要,好处有:1,二次封装后的API更加简洁,更符合个人的使用习惯:2,可以对ajax操作做一些统一处理,比如追加随机数或 ...

  7. Android 应用程序集成Google 登录及二次封装

    谷歌登录API:  https://developers.google.com/identity/sign-in/android/ 1.注册并且登录google网站 https://accounts. ...

  8. Android 应用程序集成FaceBook 登录及二次封装

    1.首先在Facebook 开发者平台注册一个账号 https://developers.facebook.com/ 开发者后台  https://developers.facebook.com/ap ...

  9. 对jquery的ajax进行二次封装

    第一种方法: $(function(){ /** * ajax封装 * url 发送请求的地址 * data 发送到服务器的数据,数组存储,如:{"username": " ...

随机推荐

  1. android device ID获取

    Android  Device ID是Android用户在Google认证过手机的设备唯一标识,当然国内很多Android手机没有经过Google认证,所以一般没有Google官方Android de ...

  2. Wpf ListView展示风格

    ListView数据绑定控件,通常是竖列展示,也可以通过改变ListView的布局来改变它的展示方式 如图展示: 主要需用修改的样式如下: <!--GridView Header样式 去除Gri ...

  3. 多线程篇七:通过Callable和Future获取线程池中单个务完成后的结果

    使用场景:如果需要拿到线程的结果,或者在线程完成后做其他操作,可以使用Callable 和 Futrue 1.定义一个线程池,向线程池中提交单个callable任务 ExecutorService t ...

  4. LDA概率图模型之贝叶斯理解

    贝叶斯.概率分布与机器学习 转自:http://www.cnblogs.com/LeftNotEasy/archive/2010/09/27/1837163.html  本文由LeftNotEasy原 ...

  5. java面试题之----get和post请求方法的区别

    GET和POST两种基本请求方法的区别 GET和POST是HTTP请求的两种基本方法,要说它们的区别,接触过WEB开发的人都能说出一二. 最直观的区别就是GET把参数包含在URL中,POST通过req ...

  6. Excel数据导入Sql Server,部分数字为Null

    在Excel中,我们时常会碰到这样的字段(最常见的就是电话号码),即有纯数字的(如没有带区号的电话号码),又有数字和其它字符混合 (如“区号-电 话号码”)的数据,在导入SQLServer过程中,会发 ...

  7. 【Leetcode】【Easy】String to Integer (atoi)

    Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. ...

  8. 【Leetcode】【Easy】Remove Element

    Given an array and a value, remove all instances of that value in place and return the new length. T ...

  9. Angular 5.x 学习笔记(1) - 模板语法

    Angular 5.x Template Syntax Learn Note Angular 5.x 模板语法学习笔记 标签(空格分隔): Angular Note on github.com 上手 ...

  10. ul自适应li问题

    内容提要: li浮动时ul高度为0,解决ul自适应高度的几种方法 在网页设计中,常常需要对li标签做浮动效果,但是在不同浏览器中会遇到兼容性问题,比如IE中会出现ul高度为0的情况,是效果不能达到预期 ...