#import//網(wǎng)絡(luò)請(qǐng)求的根路徑
#define rootPath? @"http://jufeng.veyd.cn"
@interface UploadParam : NSObject
/**
*? 圖片的二進(jìn)制數(shù)據(jù)
*/
@property (nonatomic, strong) NSData *data;
/**
*? 服務(wù)器對(duì)應(yīng)的參數(shù)名稱
*/
@property (nonatomic, copy) NSString *name;
/**
*? 文件的名稱(上傳到服務(wù)器后,服務(wù)器保存的文件名)
*/
@property (nonatomic, copy) NSString *filename;
/**
*? 文件的MIME類型(image/png,image/jpg等)
*/
@property (nonatomic, copy) NSString *mimeType;
@end
/**
*? 網(wǎng)絡(luò)請(qǐng)求類型
*/
typedef NS_ENUM(NSUInteger,HttpRequestType) {
/**
*? get請(qǐng)求
*/
HttpRequestTypeGet = 0,
/**
*? post請(qǐng)求
*/
HttpRequestTypePost
};
typedef NS_ENUM(NSUInteger, NetWorkStatus) {
NetWorkUnNow,//未知網(wǎng)絡(luò)
NetWorkWifi,//無線網(wǎng)
NetWork4Gor3G,//手機(jī)4G或者3G網(wǎng)絡(luò)
NetWorkNot,//沒有網(wǎng)
};
@interface NetWorkHelper : NSObject
/*!網(wǎng)絡(luò)狀態(tài)*/
@property(nonatomic, assign)NetWorkStatus networkStatus;
/*!請(qǐng)求的全局參數(shù)nkey*/
@property(nonatomic, copy)NSString *nkey;
/*!請(qǐng)求的全局參數(shù)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;
/*!監(jiān)聽網(wǎng)絡(luò)狀態(tài)*/
- (void)jiantingNetWorkStatus;
/**
*? 發(fā)送get請(qǐng)求
*
*? @param URLString? 請(qǐng)求的網(wǎng)址字符串
*? @param parameters 請(qǐng)求的參數(shù)
*? @param success? ? 請(qǐng)求成功的回調(diào)
*? @param failure? ? 請(qǐng)求失敗的回調(diào)
*/
+ (void)getWithURLString:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(id responseObject))success
failure:(void (^)(NSError *error))failure;
/**
*? 發(fā)送post請(qǐng)求
*
*? @param URLString? 請(qǐng)求的網(wǎng)址字符串
*? @param parameters 請(qǐng)求的參數(shù)
*? @param success? ? 請(qǐng)求成功的回調(diào)
*? @param failure? ? 請(qǐng)求失敗的回調(diào)
*/
+ (void)postWithURLString:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(id responseObject))success
failure:(void (^)(NSError *error))failure;
/**
*? 發(fā)送網(wǎng)絡(luò)請(qǐng)求
*
*? @param URLString? 請(qǐng)求的網(wǎng)址字符串
*? @param parameters? 請(qǐng)求的參數(shù)
*? @param type? ? ? ? 請(qǐng)求的類型
*
*/
+ (void)requestWithURLString:(NSString *)URLString
parameters:(id)parameters
type:(HttpRequestType)type
success:(void (^)(id responseObject))success
failure:(void (^)(NSError *error))failure;
/**
*? 上傳圖片
*
*? @param URLString? 上傳圖片的網(wǎng)址字符串
*? @param parameters? 上傳圖片的參數(shù)
*? @param uploadParam 上傳圖片的信息
*? @param success? ? 上傳成功的回調(diào)
*? @param failure? ? 上傳失敗的回調(diào)
*/
+ (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//登陸賬號(hào)用到的類
//#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 ****************監(jiān)聽網(wǎng)絡(luò)狀態(tài)**********************- (void)jiantingNetWorkStatus{? ? //檢測網(wǎng)絡(luò)狀態(tài)? ? AFNetworkReachabilityManager *statusManager = [AFNetworkReachabilityManager sharedManager];? ?
?[statusManager startMonitoring];??
? [statusManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {? ? ? ? switch (status) {? ? ? ? ? ? case AFNetworkReachabilityStatusUnknown:? ? ? ? ? ? {? ? ? ? ? ? ? ? // 位置網(wǎng)絡(luò)? ? ? ? ? ? ? ? //MHLog(@"")? ? ? ? ? ? ? ? //NSLog(@"未知網(wǎng)絡(luò)");? ? ? ? ? ? ? ? _instance.networkStatus = NetWorkUnNow;? ? ? ? ?
?? ? ? ? ? ? ? ? ? }? ? ? ? ? ? ? ? break;? ? ?
?? ? ? case AFNetworkReachabilityStatusNotReachable:? ?
?? ? ? ? {? ? ? ? ? ? ? ? // 無法聯(lián)網(wǎng)? ? ? ? ? ? ??
? //NSLog(@"無法聯(lián)網(wǎng)");? ? ? ?
?? ? ? ? _instance.networkStatus = NetWorkNot;? ? ??
? ? ? ? ? ? ? ? ? ? ? }? ? ? ? ? ? ? ? break;? ? ??
? ? ? case AFNetworkReachabilityStatusReachableViaWWAN:? ? ? ? ? ? {? ? ? ? ? ?
?? ? // 手機(jī)自帶網(wǎng)絡(luò)? ? ? ? ? ? ??
? //NSLog(@"當(dāng)前使用的是2G/3G/4G網(wǎng)絡(luò)");? ??
? ? ? ? ? ? _instance.networkStatus = NetWork4Gor3G;? ??
? ? ? ? ? ? ? ? ? ? ? ? }? ? ? ? ? ? ? ? break;? ? ? ? ?
?? case AFNetworkReachabilityStatusReachableViaWiFi:? ??
? ? ? ? {? ? ? ? ? ? ? ?
?// WIFI? ? ? ? ? ? ? ?
?//NSLog(@"當(dāng)前在WIFI網(wǎng)絡(luò)下");? ? ? ? ? ? ? ? _instance.networkStatus = NetWorkWifi;? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? }? ? ? ? }? ? }];? ?
?}
#pragma mark -- GET請(qǐng)求 --
+ (void)getWithURLString:(NSString *)URLString? ? ? ? ? ? ? parameters:(id)parameters? ? ? ? ? ? ? ? success:(void (^)(id))success? ? ? ? ? ? ??
? failure:(void (^)(NSError *))failure {? ? ? ? ////////////////////////? ? ? ? ? ? AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];? ?
?manager.requestSerializer.timeoutInterval = 10;? ? ??
? ? ? //根據(jù)網(wǎng)絡(luò)狀態(tài)設(shè)置不同的緩存策略? ? ? ?
?NetWorkStatus status = [NetWorkHelper sharedInstance].networkStatus;? ??
? ? switch (status) {? ?
?? ? ? ? case NetWorkUnNow:? ??
? ? ? ? {? ? ? ? ? ? ??
? // 位置網(wǎng)絡(luò)? ? ? ? ? ? ??
? //MHLog(@"")? ? ? ? ? ? ? ?
?//默認(rèn)緩存策略? ? ? ? ? ??
? ? [manager.requestSerializer setCachePolicy:NSURLRequestUseProtocolCachePolicy];? ? ? ? ? ? }? ? ? ? ? ? ? ? break;? ? ? ? ? ??
case NetWorkNot:? ? ? ? ? ? {? ? ? ? ? ? ? ??
// 無法聯(lián)網(wǎng)? ? ? ? ? ? ? ?
?// NSLog(@"無法聯(lián)網(wǎng)");? ? ? ? ? ? ?
?? //加載本地緩存數(shù)據(jù)? ? ? ? ? ? ? ?
?[manager.requestSerializer setCachePolicy:NSURLRequestReturnCacheDataElseLoad];? ? ? ? ? ? ? ? ? ? ? ? ? ? }? ? ? ? ? ??
? ? break;? ? ? ??
? ? case NetWork4Gor3G:? ? ? ? ? ? {? ? ? ? ? ??
? ? // 手機(jī)自帶網(wǎng)絡(luò) ? ?
?? ? ? ? ? // NSLog(@"當(dāng)前使用的是2G/3G/4G網(wǎng)絡(luò)");? ??
? ? ? ? ? ? //做網(wǎng)絡(luò)緩存(有緩存加載緩存,沒緩存請(qǐng)求)? ? ? ? ? ? ??
? [manager.requestSerializer setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];? ? ? ? ? ? }? ? ? ? ? ? ? ? break;? ? ? ? ? ? case NetWorkWifi:? ? ? ? ? ? {? ? ? ? ? ? ? ? // WIFI? ? ? ? ? ? ? ? // NSLog(@"當(dāng)前在WIFI網(wǎng)絡(luò)下");? ? ? ? ?
?? ? ? //做網(wǎng)絡(luò)緩存(不管有無緩存都請(qǐng)求數(shù)據(jù))? ? ? ? ? ? ? ? [manager.requestSerializer setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];? ? ??
? ? ? }? ? ? ? }? ? ? ? ? ? /**? ? *? 可以接受的類型? ? */? ? ? ? //設(shè)置加密策略? ? //[manager setSecurityPolicy:[self customSecurityPolicy]];? ? manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/x-javascript",@"text/json",@"application/json" ,nil];? ? ??
? /**? ? *? 請(qǐng)求隊(duì)列的最大并發(fā)數(shù)? ? */? ? //? ? manager.operationQueue.maxConcurrentOperationCount = 5;? ? /**? ? *? 請(qǐng)求超時(shí)的時(shí)間? ? */? ? //manager.requestSerializer.timeoutInterval = 30;? ?
?? ? //url請(qǐng)求參數(shù)? ? NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:parameters];
? ? //添加全局參數(shù)? ? ? ?
?[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請(qǐng)求 --+ (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添加數(shù)字證書? ?
?//[manager setSecurityPolicy:[self customSecurityPolicy]];
//? ? manager.responseSerializer = [AFHTTPResponseSerializer serializer];? ? manager.requestSerializer = [AFHTTPRequestSerializer serializer];??
? //返回?cái)?shù)據(jù)的序列化器?
?? manager.responseSerializer = [AFJSONResponseSerializer serializer];? ? manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/x-javascript",@"text/json", @"application/json", nil];??
? //url請(qǐng)求參數(shù)?
?? NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:parameters];? ? ? // 添加全局參數(shù)? ?
?[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網(wǎng)絡(luò)請(qǐng)求 --+ (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 ****************單向驗(yàn)證證書**********************
+ (AFSecurityPolicy *)customSecurityPolicy
{
//先導(dǎo)入證書,找到證書的路徑
NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"1_www.ms1491.com_bundle" ofType:@"cer"];
NSData *certData = [NSData dataWithContentsOfFile:cerPath];
//AFSSLPinningModeCertificate 使用證書驗(yàn)證模式
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
//allowInvalidCertificates 是否允許無效證書(也就是自建的證書),默認(rèn)為NO
securityPolicy.allowInvalidCertificates = YES;
//validatesDomainName 是否需要驗(yàn)證域名依痊,默認(rèn)為YES铝阐;
//假如證書的域名與你請(qǐng)求的域名不一致讥珍,需把該項(xiàng)設(shè)置為NO诽凌;如設(shè)成NO的話捕犬,即服務(wù)器使用其他可信任機(jī)構(gòu)頒發(fā)的證書矾瑰,也可以建立連接砖茸,這個(gè)非常危險(xiǎn),建議打開殴穴。
//置為NO凉夯,主要用于這種情況:客戶端請(qǐng)求的是子域名,而證書上的是另外一個(gè)域名采幌。因?yàn)镾SL證書上的域名是獨(dú)立的劲够;
//如置為NO,建議自己添加對(duì)應(yīng)域名的校驗(yàn)邏輯休傍。
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