#import//网络请求的根路径
#define rootPath @"http://jufeng.veyd.cn"
@interface UploadParam : NSObject
/**
* 图片的二进制数据
*/
@property (nonatomic, strong) NSData *data;
/**
* 服务器对应的参数名称
*/
@property (nonatomic, copy) NSString *name;
/**
* 文件的名称(上传到服务器后,服务器保存的文件名)
*/
@property (nonatomic, copy) NSString *filename;
/**
* 文件的MIME类型(image/png,image/jpg等)
*/
@property (nonatomic, copy) NSString *mimeType;
@end
/**
* 网络请求类型
*/
typedef NS_ENUM(NSUInteger,HttpRequestType) {
/**
* get请求
*/
HttpRequestTypeGet = 0,
/**
* post请求
*/
HttpRequestTypePost
};
typedef NS_ENUM(NSUInteger, NetWorkStatus) {
NetWorkUnNow,//未知网络
NetWorkWifi,//无线网
NetWork4Gor3G,//手机4G或者3G网络
NetWorkNot,//没有网
};
@interface NetWorkHelper : NSObject
/*!网络状态*/
@property(nonatomic, assign)NetWorkStatus networkStatus;
/*!请求的全局参数nkey*/
@property(nonatomic, copy)NSString *nkey;
/*!请求的全局参数sessionid*/
@property(nonatomic, copy)NSString *sessionid;
@property (nonatomic,assign)NSString *time;
@property (nonatomic ,copy)NSString *sign;
@property (nonatomic, copy)NSString *token;
@property (nonatomic, copy)NSString *uid;
@property (nonatomic, copy)NSString *facility;
/*!单利*/
+ (instancetype)sharedInstance;
/*!监听网络状态*/
- (void)jiantingNetWorkStatus;
/**
* 发送get请求
*
* @param URLString 请求的网址字符串
* @param parameters 请求的参数
* @param success 请求成功的回调
* @param failure 请求失败的回调
*/
+ (void)getWithURLString:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(id responseObject))success
failure:(void (^)(NSError *error))failure;
/**
* 发送post请求
*
* @param URLString 请求的网址字符串
* @param parameters 请求的参数
* @param success 请求成功的回调
* @param failure 请求失败的回调
*/
+ (void)postWithURLString:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(id responseObject))success
failure:(void (^)(NSError *error))failure;
/**
* 发送网络请求
*
* @param URLString 请求的网址字符串
* @param parameters 请求的参数
* @param type 请求的类型
*
*/
+ (void)requestWithURLString:(NSString *)URLString
parameters:(id)parameters
type:(HttpRequestType)type
success:(void (^)(id responseObject))success
failure:(void (^)(NSError *error))failure;
/**
* 上传图片
*
* @param URLString 上传图片的网址字符串
* @param parameters 上传图片的参数
* @param uploadParam 上传图片的信息
* @param success 上传成功的回调
* @param failure 上传失败的回调
*/
+ (void)uploadWithURLString:(NSString *)URLString
parameters:(id)parameters
uploadParam:(UploadParam *)uploadParam
success:(void (^)())success
failure:(void (^)(NSError *error))failure;
@end
//.文件
#import "NetWorkHelper.h"#import#import "JFLoginTool.h"#import//登陆账号用到的类
//#import "MHLoginTool.h"
@implementation NetWorkHelperstatic
NetWorkHelper * _instance = nil;
+ (instancetype)sharedInstance { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instance = [[NetWorkHelper alloc] init];
[_instance jiantingNetWorkStatus]; }); return _instance;}
#pragma mark ****************监听网络状态**********************- (void)jiantingNetWorkStatus{ //检测网络状态 AFNetworkReachabilityManager *statusManager = [AFNetworkReachabilityManager sharedManager];
[statusManager startMonitoring];
[statusManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { switch (status) { case AFNetworkReachabilityStatusUnknown: { // 位置网络 //MHLog(@"") //NSLog(@"未知网络"); _instance.networkStatus = NetWorkUnNow;
} break;
case AFNetworkReachabilityStatusNotReachable:
{ // 无法联网
//NSLog(@"无法联网");
_instance.networkStatus = NetWorkNot;
} break;
case AFNetworkReachabilityStatusReachableViaWWAN: {
// 手机自带网络
//NSLog(@"当前使用的是2G/3G/4G网络");
_instance.networkStatus = NetWork4Gor3G;
} break;
case AFNetworkReachabilityStatusReachableViaWiFi:
{
// WIFI
//NSLog(@"当前在WIFI网络下"); _instance.networkStatus = NetWorkWifi; } } }];
}
#pragma mark -- GET请求 --
+ (void)getWithURLString:(NSString *)URLString parameters:(id)parameters success:(void (^)(id))success
failure:(void (^)(NSError *))failure { //////////////////////// AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer.timeoutInterval = 10;
//根据网络状态设置不同的缓存策略
NetWorkStatus status = [NetWorkHelper sharedInstance].networkStatus;
switch (status) {
case NetWorkUnNow:
{
// 位置网络
//MHLog(@"")
//默认缓存策略
[manager.requestSerializer setCachePolicy:NSURLRequestUseProtocolCachePolicy]; } break;
case NetWorkNot: {
// 无法联网
// NSLog(@"无法联网");
//加载本地缓存数据
[manager.requestSerializer setCachePolicy:NSURLRequestReturnCacheDataElseLoad]; }
break;
case NetWork4Gor3G: {
// 手机自带网络
// NSLog(@"当前使用的是2G/3G/4G网络");
//做网络缓存(有缓存加载缓存,没缓存请求)
[manager.requestSerializer setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; } break; case NetWorkWifi: { // WIFI // NSLog(@"当前在WIFI网络下");
//做网络缓存(不管有无缓存都请求数据) [manager.requestSerializer setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
} } /** * 可以接受的类型 */ //设置加密策略 //[manager setSecurityPolicy:[self customSecurityPolicy]]; manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/x-javascript",@"text/json",@"application/json" ,nil];
/** * 请求队列的最大并发数 */ // manager.operationQueue.maxConcurrentOperationCount = 5; /** * 请求超时的时间 */ //manager.requestSerializer.timeoutInterval = 30;
//url请求参数 NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:parameters];
//添加全局参数
[manager GET:[NSString stringWithFormat:@"%@%@", rootPath, URLString] parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { if (success) { if ([responseObject[@"code"] isEqualToString:@"04"]) { [JFLoginTool showLoginVCWithCurrentVC];
//[JFLoginTool showLoginVCWithCurrentVC:nil islogin:Login];
}else{
success(responseObject);
}
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) {
failure(error);
} }];
}
#pragma mark -- POST请求 --+ (void)postWithURLString:(NSString *)URLString parameters:(id)parameters success:(void (^)(id))success failure:(void (^)(NSError *))failure { NSString * timeC = [NSString stringWithFormat:@"%ld",time(NULL)]; NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"4886659db1dfc63a05583503aff1ce9454d01bfc",@"key",timeC,@"time",@"ios",@"facility",nil];
NSArray *allKeyArray = [dict allKeys];
NSArray *afterSortKeyArray = [allKeyArray sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) { return NSOrderedDescending; }];
//通过排列的key值获取value NSMutableArray *valueArray = [NSMutableArray array];
for (NSString *sortsing in afterSortKeyArray) { NSString *valueString = [dict objectForKey:sortsing];
[valueArray addObject:valueString];
} NSMutableArray *signArray = [NSMutableArray array];
for (int i = 0 ; i < afterSortKeyArray.count; i++) { NSString * keyValue = [NSString stringWithFormat:@"%@=%@",afterSortKeyArray[i],valueArray[i]];
[signArray addObject:keyValue]; } NSString *str = @"";
for (NSString *temp in signArray) { str = [str stringByAppendingString:[NSString stringWithFormat:@"%@&",temp]];
}
NSString *shalStr = [str substringToIndex:str.length - 1];
NSLog(@"shlstr = %@",shalStr);
// shalStr = [shalStr sha1String];
shalStr = [self getSha1String:shalStr];
NSLog(@"sign = %@", shalStr);
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; manager.requestSerializer.timeoutInterval = 15;
//HTTPS添加数字证书
//[manager setSecurityPolicy:[self customSecurityPolicy]];
// manager.responseSerializer = [AFHTTPResponseSerializer serializer]; manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//返回数据的序列化器
manager.responseSerializer = [AFJSONResponseSerializer serializer]; manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/x-javascript",@"text/json", @"application/json", nil];
//url请求参数
NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:parameters]; // 添加全局参数
[manager.requestSerializer setValue:timeC forHTTPHeaderField:@"time"]; [manager.requestSerializer setValue:shalStr forHTTPHeaderField:@"sign"]; [manager.requestSerializer setValue:@"ios" forHTTPHeaderField:@"facility"]; [manager.requestSerializer setValue:@"" forHTTPHeaderField:@"uid"]; [manager.requestSerializer setValue:@"" forHTTPHeaderField:@"token"];
// [dic setValue:timeC forKey:@"time"];
//
//这是.h文件 property(nonatomic ,copy)NSString *nkey// [dic setValue:[NetWorkHelper sharedInstance].nkey forKey:@"nkey"];
//
[dic setValue: == nil ? shalStr:[NetWorkHelper sharedInstance].sessionid forKey:@"sign"];// [dic setValue:[NetWorkHelper sharedInstance].time == nil ? timeC:[NetWorkHelper sharedInstance].sessionid forKey:@"time"];
// [dic setValue:[NetWorkHelper sharedInstance].sign == nil ? shalStr:[NetWorkHelper sharedInstance].sessionid forKey:@"sign"];
// [dic setValue:[NetWorkHelper sharedInstance].facility == nil ? @"ios":[NetWorkHelper sharedInstance].sessionid forKey:@"facility"];////
// [dic setValue:[NetWorkHelper sharedInstance].uid == nil ? @"":[NetWorkHelper sharedInstance].sessionid forKey:@"uid"];
// [dic setValue:[NetWorkHelper sharedInstance].token == nil ? @"":[NetWorkHelper sharedInstance].sessionid forKey:@"token"];
// [manager POST:[NSString stringWithFormat:@"%@%@", rootPath, URLString] parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { if (success) { if ([responseObject[@"code"] isEqualToString:@"04"]) { }else{ success(responseObject);
}
}
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { if (failure) { failure(error); } }];
}#pragma mark -- POST/GET网络请求 --+ (void)requestWithURLString:(NSString *)URLString parameters:(id)parameters type:(HttpRequestType)type success:(void (^)(id))success failure:(void (^)(NSError *))failure { AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer.timeoutInterval = 15; manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/x-javascript",@"text/json", nil]; switch (type) { case HttpRequestTypeGet: { [manager GET:URLString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { if (success) { success(responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { if (failure) { failure(error); } }];
} break;
case HttpRequestTypePost:
{ [manager POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { if (success) { success(responseObject);
} } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { if (failure) { failure(error); } }];
} break; }}#pragma mark -- 上传图片 --+ (void)uploadWithURLString:(NSString *)URLString parameters:(id)parameters uploadParam:(UploadParam *)uploadParam success:(void (^)())success failure:(void (^)(NSError *))failure { AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/x-javascript",@"text/json", nil]; [manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id_Nonnull formData) {
[formData appendPartWithFileData:uploadParam.data name:uploadParam.name fileName:uploadParam.filename mimeType:uploadParam.mimeType];
} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (success) {
success(responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) {
failure(error);
}
}];
}
#pragma mark ****************单向验证证书**********************
+ (AFSecurityPolicy *)customSecurityPolicy
{
//先导入证书,找到证书的路径
NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"1_www.ms1491.com_bundle" ofType:@"cer"];
NSData *certData = [NSData dataWithContentsOfFile:cerPath];
//AFSSLPinningModeCertificate 使用证书验证模式
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
//allowInvalidCertificates 是否允许无效证书(也就是自建的证书),默认为NO
securityPolicy.allowInvalidCertificates = YES;
//validatesDomainName 是否需要验证域名,默认为YES;
//假如证书的域名与你请求的域名不一致,需把该项设置为NO;如设成NO的话,即服务器使用其他可信任机构颁发的证书,也可以建立连接,这个非常危险,建议打开。
//置为NO,主要用于这种情况:客户端请求的是子域名,而证书上的是另外一个域名。因为SSL证书上的域名是独立的;
//如置为NO,建议自己添加对应域名的校验逻辑。
securityPolicy.validatesDomainName = NO;
NSSet *set = [[NSSet alloc] initWithObjects:certData, nil];
securityPolicy.pinnedCertificates = set;
return securityPolicy;
}
//sha1加密方式
+ (NSString *)getSha1String:(NSString *)srcString{
const char *cstr = [srcString cStringUsingEncoding:NSUTF8StringEncoding];
NSData *data = [NSData dataWithBytes:cstr length:srcString.length];
uint8_t digest[CC_SHA1_DIGEST_LENGTH];
CC_SHA1(data.bytes, data.length, digest);
NSMutableString* result = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) {
[result appendFormat:@"%02x", digest[i]];
}
return result;
}
@end