123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365 |
- #import "ERequest.h"
- #import "ServerManager.h"
- #import "NSString+http.h"
- #import "NSData+http.h"
- #import "SKDefine.h"
- #import <AFNetworking/AFNetworking.h>
- #define KEY_AES @"a3ca2bcd4bcda6c7" //加密
- @implementation ERequest
- + (NSDictionary*)setHeaders:(NSDictionary*)param isEncrypt:(BOOL)isEncrypt contentType:(NSString*)contentType {
- //当前语言
- NSString* localization = [[[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"] firstObject];
-
- //当前时区,timestamp
- NSString* timezone = [self getTimezone];
- NSInteger interval = [[NSDate date] timeIntervalSince1970];
- NSString* timestamp = [NSString stringWithFormat:@"%ld", interval];
-
- //iPhone
- NSDictionary *infoDic = [NSBundle mainBundle].infoDictionary;
- NSString* iphoneAppVersion = infoDic[@"CFBundleShortVersionString"];
- NSString* iphoneSystemVersion = [[UIDevice currentDevice] systemVersion];
- NSString* iphoneModel = [[UIDevice currentDevice] name];
-
- //noncestr
- NSString* noncestr = [[NSString uniqueString] md5HexEncode];
-
- //token
- NSString* token = [self getToken];
-
- //Headers
- NSMutableDictionary *headers = [[NSMutableDictionary alloc] init];
- headers[@"Content-type"] = contentType;
- headers[@"Accept-Version"] = @"1.0.0";
- headers[@"accept-language"] = @"zh";
- headers[@"noncestr"] = noncestr;
- headers[@"Localization"] = localization;
- //W303B
- headers[@"X-Device-System"] = @"ios";
- headers[@"X-Device-System-Version"] = iphoneSystemVersion;
- headers[@"X-Device-Software-Version"] = iphoneAppVersion;
- headers[@"X-Device-Model"] = iphoneModel;
- headers[@"X-Device-Timezone"] = timezone;
- headers[@"X-Device-Timestamp"] = timestamp;
-
- //H210
- headers[@"sys"] = @"ios";
- headers[@"sys-no"] = iphoneSystemVersion;
- headers[@"timestamp"] = timestamp;
- headers[@"device-no"] = [SKDefine getModel];
- headers[@"device-model"] = [SKDefine getModel];
- headers[@"device-mac"] = [self getMacAddress];
- headers[@"device-type"] = @"3";
-
- //国内项目
- headers[@"X-System"] = @"IOS";
- headers[@"X-System-Version"] = iphoneSystemVersion;
- headers[@"X-Software-Version"] = iphoneAppVersion;
- headers[@"X-Manufacturer"] = @"Apple";
- headers[@"X-Time-Zone"] = timezone;
- headers[@"X-Timestamp"] = timestamp;
- headers[@"X-Request-Id"] = [NSString stringWithFormat:@"%@-%@", noncestr, timestamp];
-
-
- if (token && token.length > 0) {
- NSString* authorization = [NSString stringWithFormat:@"%@ %@", @"Bearer", token];
- headers[@"Authorization"] = authorization;
- }
-
- #ifdef SK_FUNCTION_ENCRYPT
- if (isEncrypt) {
- headers[@"token"] = token == nil ? @"" : token;
- if (param) {
- NSData* jsonData = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingFragmentsAllowed error:nil];
- NSString* data = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
- data = [data URLEncode];
- NSString* sign = [NSString stringWithFormat:@"noncestr=%@×tamp=%@&token=%@&data=%@", noncestr, timestamp, token, data];
- NSData *signData = [sign dataUsingEncoding:NSUTF8StringEncoding];
- NSString *signBase64 = [signData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
- sign = [signBase64 md5HexEncode];
- headers[@"sign"] = sign;
- }
- }
- #endif
- return headers;
- }
- + (NSData*)encryptionBody:(NSDictionary*)param isEncrypt:(BOOL)isEncrypt {
- #ifdef SK_FUNCTION_ENCRYPT
- if (isEncrypt) {
- NSString* key = KEY_AES;
- NSString* iv = KEY_AES;
- NSData* jsonData = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingFragmentsAllowed error:nil];
- NSData *jsonDataAES = [jsonData AES128EncryptWithKey:key gIv:iv];
- //NSString *signBase64 = [jsonDataAES base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
- return [jsonDataAES base64EncodedDataWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
- }
- #endif
- return [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:nil];
- }
- + (void)httpRequest:(NSDictionary*)param
- path:(NSString*)path
- httpURL:(NSString*)httpURL
- httpMethod:(NSString*)httpMethod
- onSuccess:(void(^)(NSDictionary* result))success
- onFailure:(void(^)(NSError* error))failure {
-
- //如果是服务器 >= 2,不加密
- NSInteger type = [ServerManager getServerType];
- BOOL isEncrypt = type >= 2 ? NO : YES;
-
- param = [self isGET:httpMethod] ? @{} : param;
- httpURL = [path isStartWithString:@"?"] ? [NSString stringWithFormat:@"%@%@", httpURL, path] : [NSString stringWithFormat:@"%@/%@", httpURL, path];
- [self httpRequest:param httpURL:httpURL httpMethod:httpMethod httpEncrypt:isEncrypt onSuccess:success onFailure:failure];
- }
- + (void)httpRequest:(NSDictionary*)param
- httpURL:(NSString*)httpURL
- httpMethod:(NSString*)httpMethod
- onSuccess:(void(^)(NSDictionary* result))success
- onFailure:(void(^)(NSError* error))failure {
-
- //如果是服务器 >= 2,不加密
- NSInteger type = [ServerManager getServerType];
- BOOL isEncrypt = type >= 2 ? NO : YES;
-
- [self httpRequest:param httpURL:httpURL httpMethod:httpMethod httpEncrypt:isEncrypt onSuccess:success onFailure:failure];
- }
- + (void)httpRequest:(NSDictionary*)param
- httpURL:(NSString*)httpURL
- httpMethod:(NSString*)httpMethod
- httpEncrypt:(BOOL)isEncrypt
- onSuccess:(void(^)(NSDictionary* result))success
- onFailure:(void(^)(NSError* error))failure {
-
- NSString* contentType = @"application/json";
- NSDictionary* header = [self setHeaders:param isEncrypt:isEncrypt contentType:contentType];
- NSData *body = [self encryptionBody:param isEncrypt:isEncrypt];
-
- [self httpRequest:param httpMethod:httpMethod httpURL:httpURL httpHeader:header body:body onSuccess:success onFailure:failure];
- }
- + (void)httpRequest:(NSDictionary*)param
- httpURL:(NSString*)httpURL
- httpEncrypt:(BOOL)isEncrypt
- fileData:(NSData*)fileData
- fileName:(NSString*)fileName
- mimeType:(NSString*)mimeType
- onSuccess:(void(^)(NSDictionary* result))success
- onFailure:(void(^)(NSError* error))failure {
- NSString* httpMethod = @"POST";
- NSString* contentType = @"multipart/form-data";
- NSDictionary* header = [self setHeaders:param isEncrypt:isEncrypt contentType:contentType];
-
- if (!httpMethod || [httpMethod isEqualToString:@""])
- return;
- if (!httpURL || [httpURL isEqualToString:@""])
- return;
- NSString* allUrl = [self joinHttpDomains:httpURL];
- HDNormalLog(([NSString stringWithFormat:@"------->>> 【%@】%@\n header:%@\n param:%@\n", httpMethod, allUrl, header, param]));
-
-
- AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
- manager.requestSerializer = [AFJSONRequestSerializer serializer];
- manager.requestSerializer.timeoutInterval = 15;
- for (NSString* key in header.allKeys) {
- [manager.requestSerializer setValue:header[key] forHTTPHeaderField:key];
- }
- manager.responseSerializer = [AFJSONResponseSerializer serializer];
- [manager.securityPolicy setAllowInvalidCertificates:YES];
- [manager.securityPolicy setValidatesDomainName:NO];
-
- [manager POST:allUrl parameters:param headers:@{} constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
- [formData appendPartWithFileData:fileData name:@"file" fileName:fileName mimeType:mimeType];
- } progress:^(NSProgress * _Nonnull uploadProgress) {
-
- } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
-
- [ERequest httpCallback:httpMethod httpURL:allUrl response:task.response responseObject:responseObject error:nil onSuccess:success onFailure:failure];
- } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
-
- [ERequest httpCallback:httpMethod httpURL:allUrl response:task.response responseObject:nil error:error onSuccess:success onFailure:failure];
- }];
- }
- + (void)httpRequest:(NSDictionary*)param
- httpMethod:(NSString*)httpMethod
- httpURL:(NSString*)httpURL
- httpHeader:(NSDictionary*)header
- body:(NSData*)body
- onSuccess:(void(^)(NSDictionary* result))success
- onFailure:(void(^)(NSError* error))failure {
-
- if (!httpMethod || [httpMethod isEqualToString:@""])
- return;
- if (!httpURL || [httpURL isEqualToString:@""])
- return;
- NSString* allUrl = [self joinHttpDomains:httpURL];
- HDNormalLog(([NSString stringWithFormat:@"------->>> 【%@】%@\n header:%@\n param:%@\n", httpMethod, allUrl, header, param]));
-
- NSMutableURLRequest* request = [[AFHTTPRequestSerializer serializer] requestWithMethod:httpMethod URLString:allUrl parameters:param error:nil];
- [request setAllHTTPHeaderFields:header];
- [request setHTTPMethod:httpMethod];
- if (![self isGET:httpMethod]) {
- [request setHTTPBody:body];
- }
-
- //创建请求任务
- AFURLSessionManager* manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
- NSURLSessionDataTask *task = [manager dataTaskWithRequest:request uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
-
- } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
-
- } completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
-
- [ERequest httpCallback:httpMethod httpURL:allUrl response:response responseObject:responseObject error:error onSuccess:success onFailure:failure];
-
- }];
- [task resume];
- }
- + (void)downloadResource:(NSString*)httpURL localPath:(NSString*)localPath callback:(void(^)(BOOL isOK))callback {
- NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:httpURL]];
- NSURLSessionDownloadTask* task = [[AFHTTPSessionManager manager] downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
- } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
- return [NSURL fileURLWithPath:localPath];
- } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
- callback(error == nil);
- }];
- [task resume];
- }
- + (void)httpCallback:(NSString*)httpMethod httpURL:(NSString*)httpURL response:(NSURLResponse*)response responseObject:(id)responseObject error:(NSError*)error onSuccess:(void(^)(NSDictionary* result))success onFailure:(void(^)(NSError* error))failure {
- //判断是否断网
- if (error && (error.code == -1009 || error.code == -1001)) {
- HDNormalLog(([NSString stringWithFormat:@"<<<------- 【%@】%@\n ########### %@ ########### \n", httpMethod, httpURL, error.userInfo[@"NSLocalizedDescription"]]));
- failure(error);
- } else {
- NSInteger statusCode = ((NSHTTPURLResponse *)response).statusCode;
- NSMutableDictionary* dic = [[NSMutableDictionary alloc] init];
- dic[@"code"] = @(statusCode);
-
- //200:请求成功
- if (statusCode == 200) {
- dic[@"data"] = responseObject;
- } else {
- [dic addEntriesFromDictionary:responseObject];
- }
-
- //判断是否Token过期
- if ([self isTokenExpiredWithResult:dic]) {
- [[NSNotificationCenter defaultCenter] postNotificationName:@"SK_TOKEN_EXPIRED" object:nil];
- }
-
- HDNormalLog(([NSString stringWithFormat:@"<<<------- 【%@】%@\n%@", httpMethod, httpURL, dic]));
- success(dic);
- }
- }
- + (void)successCallback:(NSString*)httpMethod httpURL:(NSString*)httpURL responseObject:(id)responseObject callback:(void(^)(NSDictionary *result))callback {
- HDNormalLog(([NSString stringWithFormat:@"<<<------- 【%@】%@\n%@", httpMethod, httpURL, responseObject]));
-
- //token过期
- if ([self isTokenExpiredWithResult:responseObject]) {
- [[NSNotificationCenter defaultCenter] postNotificationName:@"SK_TOKEN_EXPIRED" object:nil];
- }
- callback(responseObject);
- }
- + (void)failedCallback:(NSString*)httpMethod httpURL:(NSString*)httpURL responseObject:(id)responseObject error:(NSError*)error callback:(void(^)(NSError* error))callback {
- HDNormalLog(([NSString stringWithFormat:@"<<<------- 【%@】%@\n ########### %@ ########### \n", httpMethod, httpURL, error.userInfo[@"NSLocalizedDescription"]]));
-
- if (responseObject && [responseObject isKindOfClass:[NSDictionary class]]) {
- if ([self isTokenExpiredWithResult:responseObject]) {
- [[NSNotificationCenter defaultCenter] postNotificationName:@"SK_TOKEN_EXPIRED" object:nil];
- return;
- }
- }
- callback(error);
- }
- + (BOOL)isSuccessWithResult:(NSDictionary *)result {
- //200 成功
- NSInteger successCode = [result[@"code"] integerValue];
- if (successCode == 200) {
- return YES;
- }
- return NO;
- }
- + (BOOL)isTokenExpiredWithResult:(NSDictionary *)result {
- //Token过期,需要重新登录
- NSInteger successCode = [result[@"code"] integerValue];
- if (successCode == 405 || successCode == 401) {
- return YES;
- }
- return NO;
- }
- + (BOOL)isNeedWaitWithResult:(NSDictionary *)result {
- //406 中医提交数据,等待健康数据返回
- NSInteger successCode = [result[@"code"] integerValue];
- if (successCode == 406) {
- return YES;
- }
- return NO;
- }
- + (BOOL)isGET:(NSString*)httpMethod {
- return [self isStringEquel:httpMethod search:@"GET"];
- }
- + (BOOL)isStringEquel:(NSString*)value1 search:(NSString*)value2 {
- NSString* first = value1.trimString.uppercaseString.trimString;
- NSString* second = value2.trimString.uppercaseString.trimString;
- return [first isEqualToString:second];
- }
- + (NSString*)joinHttpDomains:(NSString*)httpURL {
- NSArray* info = [ServerManager getHttpDomains];
- NSString* url = [NSString stringWithFormat:@"%@%@", info[0], info[1]];
- if ([httpURL isEqualToString:@"/token/generate"]) {
- url = @"http://api.w303b.sikey.com.cn";
- }
- return [NSString stringWithFormat:@"%@%@",url, httpURL];
- }
- + (NSString*)joinQueryString:(NSDictionary*)dic {
- NSString* ret = @"";
- for (int i = 0; i < dic.allKeys.count; i++) {
- ret = [NSString stringWithFormat:@"%@%@=%@&", ret, dic.allKeys[i], dic.allValues[i]];
- }
- ret = [ret substringToIndex:ret.length - 1];
- return ret;
- }
- + (NSString*)getMacAddress {
- NSString* mac = [[NSUserDefaults standardUserDefaults] objectForKey:@"DeviceMacString"];
- return mac ? mac : @"";
- }
- + (NSString*)getToken {
- NSString* token = [[NSUserDefaults standardUserDefaults] objectForKey:@"sk_token"];
- return token ? token : @"";
- }
- + (NSString*)getTimezone {
- NSTimeInterval interval = [[NSTimeZone systemTimeZone] secondsFromGMTForDate:[NSDate date]];
- float timezone = interval / 3600;
- return [NSString stringWithFormat:@"%@%@%.1f", @"UTC", timezone > 0 ? @"+" : @"-", fabsf(timezone)];
- }
- + (NSString*)getTimezoneString {
- NSTimeZone* timeZone = [NSTimeZone systemTimeZone] ;///获取当前时区信息
- return timeZone.name;
- }
- @end
|