用到的框架:
底层的网络框架:AFNetworking
数据转换Model:MJExtension
主要功能有:
- 支持get、post网络请求、上传文件。
- 支持网络缓存请求,可以设置缓存有效时间和存储路径。
- 支持请求数据后自动转换Model数据。
- 支持设置超时时间、请求头参数、通用请求参数、请求参数的方式(json/key-value)
- 支持统一处理网络请求返回结果(例如提示提醒、登录失效重新登录),并且能设置开关。
整体结构说明:
- SSHttpRequestConfig:配置请求的类,设置属性可以实现对应的功能
///请求方式
typedef NS_ENUM(NSInteger, RequestType) {
RequestTypePost, //post
RequestTypeGet, //get
RequestTypeUpLoad, //上传
};
///参数上传的类型
typedef NS_ENUM(NSInteger,RequestParamsType) {
///默认key-value
RequestParamsKeyValueType,
///json
RequestParamsJsonType,
};
/*
*自定义配置属性
*/
@interface SSHttpCustomObject: NSObject
///是否自动处理错误码(网络超时,网络差等情况)
@property (nonatomic, assign) BOOL isAutoHandleError;
///是否自动处理服务器返回的数据,例如(登录失效,跳登录界面)
@property (nonatomic, assign) BOOL isAutoHandleResult;
@end
/*
*网络请求设置
*/
@interface SSHttpRequestConfig : NSObject
///请求方式
@property (nonatomic, assign) RequestType requestType;
///参数上传的类型
@property (nonatomic, assign) RequestParamsType requestParamsType;
///请求的链接
@property (nonatomic, copy) NSString *requestUrl;
///请求参数
@property (nonatomic, strong) NSDictionary *paramDict;
///请求头参数
@property (nonatomic, strong) NSDictionary *headerParams;
///配置全局参数
@property (nonatomic, strong) NSDictionary *unifiedParams;
///数据请求的sessionDataTask
@property (nonatomic, strong) NSURLSessionDataTask *dataTask;
///设置请求时间,默认30秒
@property (nonatomic, assign) NSTimeInterval timeoutInterval;
///带参数的请求链接
@property (nonatomic, readonly) NSString *paramUrl;
///带公共参数字典
@property (nonatomic, strong) NSDictionary *returnAllParam;
///自定义数据
@property (nonatomic, strong) SSHttpCustomObject *requestCustomObject;
///上传的文件
@property (nonatomic, strong) NSArray <NSData *> *fileDatas;
///图片名称
@property (nonatomic, strong) NSArray <NSString *> *names;
///上传格式
@property (nonatomic, strong) NSArray <NSString *> *mimeTypes;
///自定义网络数据缓存的路径
@property (nonatomic, copy) NSString *customCacheKey;
///默认网络数据缓存的路径
@property (nonatomic, copy) NSString *defaultCacheKey;
///缓存时间(秒),默认-1不缓存,等于0永久缓存
@property (nonatomic, assign) NSTimeInterval cacheTime;
复制代码
- SSHttpResponse:用了接收数据返回的类
typedef NS_ENUM(NSInteger, SSHttpResponseStatus) {
HttpResponseSuccess = -1,//请求成功
};
@interface SSHttpResponse : NSObject
///返回错误
@property (nonatomic, strong) NSError *responseError;
///返回数据
@property (nonatomic, strong) id responseResult;
///是否缓存数据
@property (nonatomic, assign) BOOL isCacheData;
///统一处理错误
+ (void)handelResult:(id)result
error:(NSError *)error
requestConfig:(SSHttpRequestConfig *)requestConfig{
if (error&&requestConfig.requestCustomObject.isAutoHandleError) {
switch (error.code) {
case NSURLErrorTimedOut:
{
NSLog(@"网络请求超时,请检查网络!");
}
break;
case NSURLErrorNotConnectedToInternet:
case NSURLErrorNetworkConnectionLost:
case NSURLErrorBadURL:
{
NSLog(@"当前网络不稳定,请检查网络!");
}
break;
default:
NSLog(@"发生错误,请稍后再试!");
break;
}
}
if (result && requestConfig.requestCustomObject.isAutoHandleResult) {
///处理代码
///例如登录失效,重新登录
}
}
复制代码
- SSHttpRequest:处理网络请求的类
typedef void (^ResponseResult)(SSHttpResponse *response,SSHttpRequestConfig *requestConfig);
typedef void (^LoadProgress)(NSProgress *uploadProgress);
+ (instancetype)shareRequest;
///get,post
- (void)requestWithConfig:(SSHttpRequestConfig *)requestConfig
responseResult:(ResponseResult)responseResult;
///上传
- (void)upLoadWithConfig:(SSHttpRequestConfig *)requestConfig
responseResult:(ResponseResult)responseResult
progress:(LoadProgress)progress;
复制代码
- SSCacheDataCenter:实现缓存的类
+ (instancetype)sharedCenter;
///保存缓存到指定的路径
- (void)saveHttpCacheData:(NSData *)cacheData cachePath:(NSString *)cachePath cacheTime:(NSTimeInterval)cacheTime;
///读取缓存
- (void)getHttpCacheDataFromCachePath:(NSString *)cachePath success:(void(^)(NSData *cacheData))success;
///读取基本配置缓存
- (SSCacheBaseData *)loadBaseCachePath:(NSString *)cachePath;
///移除某个缓存
- (void)removeCachesWithcachePath:(NSString *)cachePath;
///删除所有缓存
- (void)removeAllCaches;
///计算总缓存大小(单位M)
- (void)calculateCacheSizeFinish:(void(^)(double size))size;
复制代码
- SSHttpConfig:统一配置一些参数
+ (instancetype)shareConfig;
///服务器链接
@property (nonatomic, copy) NSString *httpServiceUrl;
///缓存时间(秒),默认-1不缓存,等于0永久缓存
@property (nonatomic, assign) NSTimeInterval cacheTime;
///设置请求时间,默认30秒
@property (nonatomic, assign) NSTimeInterval timeoutInterval;
///配置全局参数
@property (nonatomic, strong) NSDictionary *(^unifiedParamsConfig)(void);
///请求头参数
@property (nonatomic, strong) NSDictionary *(^headerParamsConfig)(void);
复制代码
- SSHttpModel:支持网络请求自动转model返回的类,用到MJExtension
@protocol SSHttpModelDelegate<NSObject>
@optional
///init初始化时调用
- (void)ss_init;
///返回要替换的字段字典
- (NSDictionary *)ss_replacedKeyFromPropertyName;
///返回对应的数组字段
- (NSDictionary *)ss_setupObjectClassInArray;
@end
复制代码
///get请求
+ (void)getRequestWithUrlStr:(NSString *)urlStr
paramDict:(id)paramDict
responseBlock:(ResponseHandler)responseBlock;
///get请求可配置requestConfig
+ (void)getRequestWithUrlStr:(NSString *)urlStr
paramDict:(id)paramDict
requestConfigHandle:(RequestConfigHandle)requestConfigHandle
responseBlock:(ResponseHandler)responseBlock;
///post请求
+ (void)postRequestWithUrlStr:(NSString *)urlStr
paramDict:(id)paramDict
responseBlock:(ResponseHandler)responseBlock;
///post请求可配置requestConfig
+ (void)postRequestWithUrlStr:(NSString *)urlStr
paramDict:(id)paramDict
requestConfigHandle:(RequestConfigHandle)requestConfigHandle
responseBlock:(ResponseHandler)responseBlock;
///upload
+ (void)uploadRequestWithUrlStr:(NSString *)urlStr
paramDict:(id)paramDict
responseBlock:(ResponseHandler)responseBlock
uploadProgress:(LoadProgress)progress;
复制代码
主要用法:
1. 全局设置
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
///服务器链接
[SSHttpConfig shareConfig].httpServiceUrl = @"";
///参数上传的类型
[SSHttpConfig shareConfig].requestParamsType = RequestParamsJsonType;
///配置全局参数
[[SSHttpConfig shareConfig]setUnifiedParamsConfig:^NSDictionary *{
return @{@"param1":@"",@"param2":@""};
}];
///请求头参数
[[SSHttpConfig shareConfig]setHeaderParamsConfig:^NSDictionary *{
return @{@"param1":@"",@"param2":@""};
}];
return YES;
}
2. 建立模型
@interface BaseModel : SSHttpModel
@property (nonatomic, assign) NSInteger code;
@property (nonatomic, copy) NSString *message;
@end
@interface Test_Arr_Model : NSObject
@end
@interface TestModel : BaseModel
@property (nonatomic, strong) NSArray <Test_Arr_Model *> *array;
@property (nonatomic, copy) NSString *replaceName;
@end
@implementation TestModel
//返回数组模型
- (NSDictionary *)ss_setupObjectClassInArray{
return @{@"array":[Test_Arr_Model class]};
}
//替换字段
- (NSDictionary *)ss_replacedKeyFromPropertyName{
return @{@"id":@"replaceName"};
}
@end
3. 开始请求
///get请求
[TestModel getRequestWithUrlStr:@""
paramDict:@{}
responseBlock:^(TestModel *dataObj, NSError *error, BOOL isCache) {
}];
///get请求可配置requestConfig
[TestModel getRequestWithUrlStr:@"" paramDict:@{} requestConfigHandle:^(SSHttpRequestConfig *requestConfig) {
requestConfig.useCache = YES;//缓存数据
requestConfig.timeoutInterval = 20;///设置超时时间
requestConfig.customCacheKey = @"";///自定义缓存路径
} responseBlock:^(TestModel *dataObj, NSError *error, BOOL isCache) {
}];
///post请求
[TestModel postRequestWithUrlStr:@""
paramDict:@{}
responseBlock:^(id dataObj, NSError *error, BOOL isCache) {
}];
///post请求可配置requestConfig
[TestModel postRequestWithUrlStr:@"" paramDict:@{} requestConfigHandle:^(SSHttpRequestConfig *requestConfig) {
requestConfig.useCache = YES;//缓存数据
requestConfig.timeoutInterval = 20;///设置超时时间
requestConfig.customCacheKey = @"";///自定义缓存路径
} responseBlock:^(id dataObj, NSError *error, BOOL isCache) {
}];
复制代码