一、什么是HTTP
参考HTTP
二、根据项目进行封装
- 我是基于AFNetWorking 进行封装的
- 我这边主要有三个类:NetAPIClient、HttpManager、NSObject+BHRequestSetting,还有一个HttpInfo
2.1 NetAPIClient
- 继承AFHTTPSessionManager进行Post 或 get 网络请求、上传图片和上传视频的一个统一处理,暴露接口已供外部类进行统一使用
#import "AFHTTPSessionManager.h"
@interface NetAPIClient : AFHTTPSessionManager
+ (id)sharedJsonClient;
#pragma mark - 1. Post 或 get 网络请求
/// 1. Post 或 get 网络请求
/// @param aPath 接口名
/// @param params 请求体
/// @param method 请求方式
/// @param block 返回数据
- (void)requestHttpWithPath:(NSString *)aPath withParams:(NSDictionary*)params withMethodType:(NetworkMethod)method andBlock:(void (^)(id data, NSString *msg, NSInteger code))block;
#pragma mark - 2. 外部调用Post 或 get 网络请求
/// 2. Post 或 get 网络请求
/// @param aPath 接口名
/// @param params 请求体
/// @param method 请求方式
/// @param block 返回数据
- (void)externalRequestHttpWithPath:(NSString *)aPath withParams:(NSDictionary*)params withMethodType:(NetworkMethod)method andBlock:(void (^)(id data, NSString *msg, NSInteger code))block;
#pragma mark - 3. 上传单张图片
/// 3. 上传图片 和 数据
/// @param aPath 接口名
/// @param name
/// @param image 图片
/// @param params 请求体
/// @param block 返回数据
/// @param progressBlock
- (void)requestUpFileWithPath:(NSString *)aPath name:(NSString *)name image:(UIImage *)image params:(NSDictionary *)params andBlock:(void (^)(id data, NSString *msg, NSInteger code))block progress:(void (^)(double progress))progressBlock;
#pragma mark - 4. 上传视频
/// 4. 上传视频数据
/// @param aPath 接口名
/// @param videoData 视频
/// @param block 返回数据
/// @param progressBlock
- (void)requestUpFileWithPath:(NSString *)aPath videoData:(NSData *)videoData andBlock:(void (^)(id data, NSString *msg, NSInteger code))block progress:(void (^)(double progress))progressBlock;
@end
#import "NetAPIClient.h"
#import "NSObject+BHRequestSetting.h"
#import "HttpInfo.h"
@implementation NetAPIClient
static NetAPIClient *_sharedClient = nil;
static dispatch_once_t onceToken;
+ (NetAPIClient *)sharedJsonClient {
dispatch_once(&onceToken, ^{
_sharedClient = [[NetAPIClient alloc] initWithBaseURL:[NSURL URLWithString:@""]];
[_sharedClient.requestSerializer setTimeoutInterval:15];
});
return _sharedClient;
}
- (id)initWithBaseURL:(NSURL *)url {
self = [super initWithBaseURL:url];
if (!self) {
return nil;
}
// self.responseSerializer = [AFJSONResponseSerializer serializer];
self.responseSerializer = [AFHTTPResponseSerializer serializer];
self.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/plain", @"text/javascript", @"text/json", @"text/html", nil];
// 如果是需要验证自建证书,需要设置为YES
// self.securityPolicy.allowInvalidCertificates = YES;
// 是否验证域名 Defaults to `YES`.
// self.securityPolicy.validatesDomainName = NO;
return self;
}
/// 设置请求 header(根据自己公司要求定义)
- (void)setHttpHeader {
NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
UIDevice *device = [UIDevice currentDevice];
NSString *screenSizeValue = [NSString stringWithFormat:@"%.0f*%.0f",[UIScreen mainScreen].currentMode.size.width,[UIScreen mainScreen].currentMode.size.height];
[self.requestSerializer setValue:screenSizeValue forHTTPHeaderField:@"screensize"];
if (KUser.userId && KUser.isLogin) {
[self.requestSerializer setValue:KUser.userId forHTTPHeaderField:@"userId"];
}
[self.requestSerializer setValue:@"iOS" forHTTPHeaderField:@"osType"];
[self.requestSerializer setValue:[infoDic objectForKey:@"CFBundleIdentifier"] forHTTPHeaderField:@"appId"];
}
- (NSDictionary *)getHeaders {
NSMutableDictionary *headerDict = [NSMutableDictionary dictionary];
NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
return headerDict;
}
#pragma mark - 1. Post 或 get 网络请求
- (void)requestHttpWithPath:(NSString *)aPath withParams:(NSDictionary *)params withMethodType:(NetworkMethod)method andBlock:(void (^)(id data, NSString *msg, NSInteger code))block {
if (!aPath || aPath.length <= 0) {
return;
}
aPath = [aPath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSLog(@"\n===========数据请求===%zd========\nmethod:%@\naPath:%@\nparams%@", self.tasks.count, kNetworkMethodName[method], aPath, params);
[self.requestSerializer setTimeoutInterval:5];
// [self setHttpHeader];
NSString *timestamp = [NSString stringWithFormat:@"%.0f", (double)[[NSDate date] timeIntervalSince1970]*1000];
//发起请求
switch (method) {
case Get:{
[self GET:aPath parameters:[self getPostRequestSignatureDictionary:params] headers:[self getHeaders] progress:^(NSProgress * _Nonnull downloadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
//同步cookie
[self updateCookieFromTask:task];
id data = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
if ([data isKindOfClass:[NSArray class]] || [data isKindOfClass:[NSDictionary class]]) {
[[XXHttpInfo sharedXXHttpInfo] endSuccessTTPURLResponse:(NSHTTPURLResponse *)task.response timestamp:timestamp];
block(data, @"网络请求正常!", 0);
}else {
NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSISOLatin1StringEncoding];
[[XXHttpInfo sharedXXHttpInfo] endNoJsonDataSuccessTTPURLResponse:(NSHTTPURLResponse *)task.response timestamp:timestamp content:responseStr];
block(data, @"数据异常!", -1001);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
[self umFailureTask:task error:error];
[[XXHttpInfo sharedXXHttpInfo] endFailureTask:task timestamp:timestamp error:error];
NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
NSInteger statusCode = response.statusCode;
NSString *responseStr = error.userInfo[@"com.alamofire.serialization.response.error.data"];
//如果响应头http状态码是400了则进一步查下原因
if (statusCode == 400 && responseStr) {
NSDictionary *dataDic = [responseStr mj_JSONObject];
NSLog(@"错误信息 = %@", [dataDic mj_JSONString]);
block(nil, KString(dataDic[@"msg"]), [dataDic[@"code"] integerValue]);
}else if (statusCode == 500 && responseStr) {
NSDictionary *dataDic = [responseStr mj_JSONObject];
NSLog(@"错误信息 = %@", [dataDic mj_JSONString]);
block(nil, KString(dataDic[@"msg"]), [dataDic[@"code"] integerValue]);
}else {
NSString *errorMsg = [XXHttpInfo errorMessageWithErrorCode:error.code];
block(nil, errorMsg, 10000);
NSLog(@"错误 = %@", error);
}
}];
break;
}
case Post:{
[self POST:aPath parameters:[self getPostRequestSignatureDictionary:params] headers:[self getHeaders] progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
//同步cookie
[self updateCookieFromTask:task];
id data = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
if ([data isKindOfClass:[NSArray class]] || [data isKindOfClass:[NSDictionary class]]) {
[[XXHttpInfo sharedXXHttpInfo] endSuccessTTPURLResponse:(NSHTTPURLResponse *)task.response timestamp:timestamp];
block(data, @"网络请求正常!", 0);
}else {
NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSISOLatin1StringEncoding];
[[XXHttpInfo sharedXXHttpInfo] endNoJsonDataSuccessTTPURLResponse:(NSHTTPURLResponse *)task.response timestamp:timestamp content:responseStr];
block(data, @"数据异常!", -1001);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
[self umFailureTask:task error:error];
[[XXHttpInfo sharedXXHttpInfo] endFailureTask:task timestamp:timestamp error:error];
NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
NSInteger statusCode = response.statusCode;
NSString *responseStr = error.userInfo[@"com.alamofire.serialization.response.error.data"];
//如果响应头http状态码是400了则进一步查下原因
if (statusCode == 400 && responseStr) {
NSDictionary *dataDic = [responseStr mj_JSONObject];
NSLog(@"错误信息 = %@", [dataDic mj_JSONString]);
block(nil, KString(dataDic[@"msg"]), [dataDic[@"code"] integerValue]);
}else if (statusCode == 500 && responseStr) {
NSDictionary *dataDic = [responseStr mj_JSONObject];
NSLog(@"错误信息 =%@", [dataDic mj_JSONString]);
block(nil, KString(dataDic[@"msg"]), [dataDic[@"code"] integerValue]);
}else {
NSString *errorMsg = [XXHttpInfo errorMessageWithErrorCode:error.code];
block(nil, errorMsg, 10000);
NSLog(@"错误 = %@", error);
}
}];
break;
}
default:
break;
}
}
#pragma mark - 1.2 同步cookie
- (void)updateCookieFromTask:(NSURLSessionDataTask *)task {
NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
NSDictionary *dataDict = [response.allHeaderFields mj_JSONObject];
if (dataDict[@"Set-Cookie"]) {
KUser.userCookie = dataDict[@"Set-Cookie"];
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in [cookieStorage cookies]) {
if ([cookie.name isEqualToString:@"user_id"] && [kServerUrl containsString:cookie.domain]) {
KUser.userId = cookie.value;
}
if ([cookie.name isEqualToString:@"au_token"] && [kServerUrl containsString:cookie.domain]) {
// NSLog(@"autoken=====================================%@",cookie.value);
KUser.au_token = cookie.value;
KUser.domain = cookie.domain;
KUser.cookieExpiresDate = [NSString stringWithFormat:@"%ld",(long)[cookie.expiresDate timeIntervalSince1970]];
[YZWebCookieHelper addHeaderCookie];
}
}
[[BHDomainHelper sharedDomainHelper] setAllCookie];
}
}
#pragma mark - 2. 外部调用Post 或 get 网络请求
- (void)externalRequestHttpWithPath:(NSString *)aPath withParams:(NSDictionary*)params withMethodType:(NetworkMethod)method andBlock:(void (^)(id data, NSString *msg, NSInteger code))block {
if (!aPath || aPath.length <= 0) {
return;
}
aPath = [aPath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSLog(@"\n=======【外部】数据请求===========\nmethod:%@\naPath:%@\nparams%@", kNetworkMethodName[method], aPath, params);
[self.requestSerializer setTimeoutInterval:15];
//发起请求
switch (method) {
case Get:{
[self GET:aPath parameters:[self getPostRequestSignatureDictionary:params] headers:[self getHeaders] progress:^(NSProgress * _Nonnull downloadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
id data = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
block(data, @"网络请求正常!", 0);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"错误=%@", error);
NSString *errorMsg = [NSString stringWithFormat:@"[%zd]%@", error.code, LocalizedString(@"NoNetworking")];
block(nil, errorMsg, 10000);
}];
break;
}
case Post:{
[self POST:aPath parameters:[self getPostRequestSignatureDictionary:params] headers:[self getHeaders] progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
id data = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
block(data, @"网络请求正常!", 0);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"错误 = %@", error);
NSString *errorMsg = [NSString stringWithFormat:@"[%zd]%@", error.code, LocalizedString(@"NoNetworking")];
block(nil, errorMsg, 10000);
}];
break;
}
default:
break;
}
}
#pragma mark - 3. 上传单张图片
- (void)requestUpFileWithPath:(NSString *)aPath name:(NSString *)name image:(UIImage *)image params:(NSDictionary *)params andBlock:(void (^)(id data, NSString *msg, NSInteger code))block progress:(void (^)(double progress))progressBlock {
aPath = [aPath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
[self setHttpHeader];
[self.requestSerializer setTimeoutInterval:30];
[self POST:aPath parameters:[self getPostRequestSignatureDictionary:params] headers:[self getHeaders] constructingBodyWithBlock:^(id _Nonnull formData) {
NSData *data = UIImageJPEGRepresentation(image, 1.0);
if ((float)data.length/1024 > 200) {
data = UIImageJPEGRepresentation(image, 1024*200.0/(float)data.length);
}
[formData appendPartWithFileData:data name:name fileName:@"photo.png" mimeType:@"image/jpeg"];
} progress:^(NSProgress * _Nonnull uploadProgress) {
progressBlock(uploadProgress.fractionCompleted);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
id data = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
block(data, @"success", 0);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
NSInteger statusCode = response.statusCode;
NSLog(@"statusCode = %zd, \n上传失败=%@", statusCode, error);
block(nil, [NSString stringWithFormat:@"[%zd]%@", error.code, LocalizedString(@"NoNetworking")], 10000);
}];
}
#pragma mark - 4. 上传视频
- (void)requestUpFileWithPath:(NSString *)aPath videoData:(NSData *)videoData andBlock:(void (^)(id data, NSString *msg, NSInteger code))block progress:(void (^)(double progress))progressBlock {
[self setHttpHeader];
[self.requestSerializer setTimeoutInterval:300];
[self POST:aPath parameters:[self getPostRequestSignatureDictionary:nil] headers:[self getHeaders] constructingBodyWithBlock:^(id _Nonnull formData) {
[formData appendPartWithFileData:videoData name:@"upload_video_file" fileName:@"video.mp4" mimeType:@"video/mp4"];
} progress:^(NSProgress * _Nonnull uploadProgress) {
progressBlock(uploadProgress.fractionCompleted);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
id data = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
block(data, @"success", 0);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
NSInteger statusCode = response.statusCode;
NSString *responseStr = error.userInfo[@"com.alamofire.serialization.response.error.data"];
//如果响应头http状态码是400了则进一步查下原因
if (statusCode == 400 && responseStr) {
NSDictionary *dataDic = [responseStr mj_JSONObject];
NSLog(@"错误信息 = %@", [dataDic mj_JSONString]);
block(nil, KString(dataDic[@"msg"]), [dataDic[@"code"] integerValue]);
}else if (statusCode == 500 && responseStr) {
NSDictionary *dataDic = [responseStr mj_JSONObject];
NSLog(@"错误信息 = %@", [dataDic mj_JSONString]);
block(nil, KString(dataDic[@"msg"]), [dataDic[@"code"] integerValue]);
}else {
NSLog(@"错误=%@", error);
NSString *errorMsg = error.localizedDescription;
if (!IsEmpty(errorMsg)) {
block(nil, errorMsg, 10000);
}else {
block(nil, [NSString stringWithFormat:@"[%zd]%@", error.code, LocalizedString(@"NoNetworking")], 10000);
}
}
}];
}
2.2 HttpManager
- 统一请求管理类
#import
@interface HttpManager : NSObject
+ (instancetype)sharedHttpManager;
#pragma mark - ++++++++++++ 公共 ++++++++++++++
/// 公共Get通用接口
+ (void)basic_GetWithPath:(NSString *)path params:(NSDictionary *)params andBlock:(void(^)(id data, NSString *msg, NSInteger code))block;
/// 公共Post接口
+ (void)basic_PostWithPath:(NSString *)path params:(NSDictionary *)params andBlock:(void(^)(id data, NSString *msg, NSInteger code))block;
#pragma mark - ++++++++++++ 通用接口 ++++++++++++++
/// Get通用接口
+ (void)getWithPath:(NSString *)path params:(NSDictionary *)params andBlock:(void(^)(id data, NSString *msg, NSInteger code))block;
/// Post通用接口
+ (void)postWithPath:(NSString *)path params:(NSDictionary *)params andBlock:(void(^)(id data, NSString *msg, NSInteger code))block;
#pragma mark - ++++++++++++ 静态请求 ++++++++++++++
+ (void)ms_PostWithPath:(NSString *)path params:(NSDictionary *)params andBlock:(void(^)(id data, NSString *msg, NSInteger code))block;
+ (void)ms_GetWithPath:(NSString *)path params:(NSDictionary *)params andBlock:(void(^)(id data, NSString *msg, NSInteger code))block;
#pragma mark - 2. 上传单张图片
/**
* 2. 上传图片 和 数据
*
* @param aPath 接口名
* @param image 图片
* @param params 请求体
* @param block 返回数据
*/
+(void)postFileWithPath:(NSString *)aPath name:(NSString *)name image:(UIImage *)image params:(NSDictionary *)params andBlock:(void (^)(id data, NSString *msg, NSInteger code))block progress:(void (^)(double progress))progressBlock;
#pragma mark - 3. 上传视频
/**
* 3. 上传视频
*
* @param aPath 接口名
* @param videoData 视频
* @param block 返回数据
*/
+(void)postVideoWithPath:(NSString *)aPath videoData:(NSData *)videoData andBlock:(void (^)(id data, NSString *msg, NSInteger code))block progress:(void (^)(double progress))progressBlock;
@end
#import "HttpManager.h"
#import "NetAPIClient.h"
@implementation HttpManager
+ (instancetype)sharedHttpManager {
static HttpManager *shared_manager = nil;
static dispatch_once_t pred;
dispatch_once(&pred, ^{
shared_manager = [[self alloc] init];
});
return shared_manager;
}
#pragma mark - ++++++++++++ 通用接口 ++++++++++++++
/**
* Get通用接口
*/
+ (void)getWithPath:(NSString *)path params:(NSDictionary *)params andBlock:(void(^)(id data, NSString *msg, NSInteger code))block {
[[NetAPIClient sharedJsonClient] requestHttpWithPath:[NSString stringWithFormat:@"%@%@%@", kServerUrl, @"mapi/", path] withParams:params withMethodType:Get andBlock:^(id data, NSString *msg, NSInteger code) {
block(data, msg, code);
}];
}
/**
* Post通用接口
*/
+ (void)postWithPath:(NSString *)path params:(NSDictionary *)params andBlock:(void(^)(id data, NSString *msg, NSInteger code))block {
[[NetAPIClient sharedJsonClient] requestHttpWithPath:[NSString stringWithFormat:@"%@%@%@", kServerUrl, @"mapi/", path] withParams:params withMethodType:Post andBlock:^(id data, NSString *msg, NSInteger code) {
block(data, msg, code);
}];
}
#pragma mark - ++++++++++++ 静态请求 ++++++++++++++
+ (void)ms_PostWithPath:(NSString *)path params:(NSDictionary *)params andBlock:(void(^)(id data, NSString *msg, NSInteger code))block {
[[NetAPIClient sharedJsonClient] requestHttpWithPath:[NSString stringWithFormat:@"%@%@%@", kServerUrl, @"ms_api/", path] withParams:params withMethodType:Post andBlock:^(id data, NSString *msg, NSInteger code) {
block(data, msg, code);
}];
}
+ (void)ms_GetWithPath:(NSString *)path params:(NSDictionary *)params andBlock:(void(^)(id data, NSString *msg, NSInteger code))block {
[[NetAPIClient sharedJsonClient] requestHttpWithPath:[NSString stringWithFormat:@"%@%@%@", kServerUrl, @"ms_api/", path] withParams:params withMethodType:Get andBlock:^(id data, NSString *msg, NSInteger code) {
block(data, msg, code);
}];
}
#pragma mark - 2. 上传单张图片
/**
* 2. 上传图片 和 数据
*
* @param aPath 接口名
* @param image 图片
* @param params 请求体
* @param block 返回数据
*/
+ (void)postFileWithPath:(NSString *)aPath name:(NSString *)name image:(UIImage *)image params:(NSDictionary *)params andBlock:(void (^)(id data, NSString *msg, NSInteger code))block progress:(void (^)(double progress))progressBlock {
[[NetAPIClient sharedJsonClient] requestUpFileWithPath:[NSString stringWithFormat:@"%@%@%@", kServerUrl, @"mapi/", aPath] name:name image:image params:params andBlock:^(id data, NSString *msg, NSInteger code) {
block(data, msg, code);
} progress:^(double progress) {
progressBlock(progress);
}];
}
#pragma mark - 3. 上传视频
/**
* 3. 上传视频
*
* @param aPath 接口名
* @param videoData 视频
* @param block 返回数据
*/
+(void)postVideoWithPath:(NSString *)aPath videoData:(NSData *)videoData andBlock:(void (^)(id data, NSString *msg, NSInteger code))block progress:(void (^)(double progress))progressBlock {
[[NetAPIClient sharedJsonClient] requestUpFileWithPath:[NSString stringWithFormat:@"%@%@%@", kServerUrl, @"mapi/", aPath] videoData:videoData andBlock:^(id data, NSString *msg, NSInteger code) {
block(data, msg, code);
} progress:^(double progress) {
progressBlock(progress);
}];
}
@end
2.3 NSObject+BHRequestSetting
- 封装userAgent 和 参数签名
#import
@interface NSObject (BHRequestSetting)
/// 封装userAgent
- (NSString *)userAgent;
/// post 创建一个签名后参数字典
/// @param params post请求参数字典
- (NSDictionary *)getPostRequestSignatureDictionary:(NSDictionary *)params;
@end
#import "NSObject+BHRequestSetting.h"
@implementation NSObject (BHRequestSetting)
- (NSString *)userAgent {
return [NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]];
}
- (NSDictionary *)getPostRequestSignatureDictionary:(NSDictionary *)params {
NSString *time = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]*1000];
NSMutableDictionary *returnDic = [[NSMutableDictionary alloc] initWithDictionary:params];
[returnDic setObject:time forKey:@"time"];
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in [cookieStorage cookies]) {
if ([cookie.name isEqualToString:@"c_token"]) {
[returnDic setObject:cookie.value forKey:@"c_token"];
}
}
NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch|NSNumericSearch|NSWidthInsensitiveSearch|NSForcedOrderingSearch;
NSComparator sort = ^(NSString *obj1, NSString *obj2) {
NSRange range = NSMakeRange(0, obj1.length);
return [obj1 compare:obj2 options:comparisonOptions range:range];
};
NSArray *resultArray = [returnDic.allKeys sortedArrayUsingComparator:sort];
NSMutableString *paramsString = [[NSMutableString alloc] init];
for (int i = 0; i < resultArray.count; i ++) {
NSString *key = resultArray[i];
NSString *value = returnDic[key];
NSString *addStr = [NSString stringWithFormat:@"%@=%@",key,value];
[paramsString appendString:addStr];
}
NSString *sigStr = [NSString md5:paramsString];
[returnDic setObject:sigStr forKey:@"sig"];
return returnDic;
}
@end
2.4 HttpInfo
- 主要是对网络请求成功失败 后做的日志处理
#import
#import "Singleton.h"
NS_ASSUME_NONNULL_BEGIN
@interface XXHttpInfo : NSObject
singleton_interface(XXHttpInfo)
- (void)endSuccessTTPURLResponse:(NSHTTPURLResponse *)response timestamp:(NSString *)timestamp;
- (void)endNoJsonDataSuccessTTPURLResponse:(NSHTTPURLResponse *)response timestamp:(NSString *)timestamp content:(NSString *)contentStr;
- (void)endFailureTask:(NSURLSessionDataTask *)task timestamp:(NSString *)timestamp error:(NSError *)error;
+ (BOOL)isEqualDomain:(NSURLSessionDataTask *)task;
+ (NSString *)errorMessageWithErrorCode:(NSInteger)errorCode;
@end
#import "HttpInfo.h"
#import "NetAPIClient.h"
#import "NSObject+BHRequestSetting.h"
#import "FCUUID.h"
@interface XXHttpInfo ()
/** 字典数据 */
@property (strong, nonatomic) NSMutableArray *dataArray;
@end
@implementation XXHttpInfo
singleton_implementation(XXHttpInfo)
#pragma mark - 2. 请求成功
- (void)endSuccessTTPURLResponse:(NSHTTPURLResponse *)response timestamp:(NSString *)timestamp {
// 1. url
// 2. 网络耗时
// 3. 网络请求状态码
[self nextStep];
}
- (void)endNoJsonDataSuccessTTPURLResponse:(NSHTTPURLResponse *)response timestamp:(NSString *)timestamp content:(NSString *)contentStr {
// 1. url
// 2. 网络耗时
// 3. 网络请求状态码
[self nextStep];
}
#pragma mark - 3. 请求失败
- (void)endFailureTask:(NSURLSessionDataTask *)task timestamp:(NSString *)timestamp error:(NSError *)error {
// 1. url
// 2. 网络耗时
// 3. 网络请求状态码
// 4. 判断状态
[self nextStep];
}
#pragma mark - 4. 检测数据
- (void)nextStep {
if (self.dataArray.count >= 20) {
NSData *data = [[self.dataArray mj_JSONString] dataUsingEncoding:NSUTF8StringEncoding];
[self.dataArray removeAllObjects];
[self postWithUrl:@"https://" body:data];
}
}
#pragma mark - 5. 提交日志
- (void)postWithUrl:(NSString *)url body:(NSData *)body {
}
+ (BOOL)isEqualDomain:(NSURLSessionDataTask *)task {
if ([task.originalRequest.URL.host isKindOfClass:[NSString class]]) {
return [kServerUrl containsString:task.originalRequest.URL.host];
}
return YES;
}
///设置请求 header
- (void)setHttpHeader:(NSMutableURLRequest *)request {
NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
UIDevice *device = [UIDevice currentDevice];
NSString *screenSizeValue = [NSString stringWithFormat:@"%.0f*%.0f",[UIScreen mainScreen].currentMode.size.width,[UIScreen mainScreen].currentMode.size.height];
}
+ (NSString *)errorMessageWithErrorCode:(NSInteger)errorCode {
if (errorCode == -1001) {
return @"RequestTimedOut";
}
return [NSString stringWithFormat:@"[%zd]%@", errorCode,@"NoNetworking"];
}