ERequest.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. #import "ERequest.h"
  2. #import "ServerManager.h"
  3. #import "NSString+http.h"
  4. #import "NSData+http.h"
  5. #import "SKDefine.h"
  6. #import <AFNetworking/AFNetworking.h>
  7. #define KEY_AES @"a3ca2bcd4bcda6c7" //加密
  8. @implementation ERequest
  9. + (NSDictionary*)setHeaders:(NSDictionary*)param isEncrypt:(BOOL)isEncrypt contentType:(NSString*)contentType {
  10. //当前语言
  11. NSString* localization = [[[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"] firstObject];
  12. //当前时区,timestamp
  13. NSString* timezone = [self getTimezone];
  14. NSInteger interval = [[NSDate date] timeIntervalSince1970];
  15. NSString* timestamp = [NSString stringWithFormat:@"%ld", interval];
  16. //iPhone
  17. NSDictionary *infoDic = [NSBundle mainBundle].infoDictionary;
  18. NSString* iphoneAppVersion = infoDic[@"CFBundleShortVersionString"];
  19. NSString* iphoneSystemVersion = [[UIDevice currentDevice] systemVersion];
  20. NSString* iphoneModel = [[UIDevice currentDevice] name];
  21. //noncestr
  22. NSString* noncestr = [[NSString uniqueString] md5HexEncode];
  23. //token
  24. NSString* token = [self getToken];
  25. //Headers
  26. NSMutableDictionary *headers = [[NSMutableDictionary alloc] init];
  27. headers[@"Content-type"] = contentType;
  28. headers[@"Accept-Version"] = @"1.0.0";
  29. headers[@"accept-language"] = @"zh";
  30. headers[@"noncestr"] = noncestr;
  31. headers[@"Localization"] = localization;
  32. //W303B
  33. headers[@"X-Device-System"] = @"ios";
  34. headers[@"X-Device-System-Version"] = iphoneSystemVersion;
  35. headers[@"X-Device-Software-Version"] = iphoneAppVersion;
  36. headers[@"X-Device-Model"] = iphoneModel;
  37. headers[@"X-Device-Timezone"] = timezone;
  38. headers[@"X-Device-Timestamp"] = timestamp;
  39. //H210
  40. headers[@"sys"] = @"ios";
  41. headers[@"sys-no"] = iphoneSystemVersion;
  42. headers[@"timestamp"] = timestamp;
  43. headers[@"device-no"] = [SKDefine getModel];
  44. headers[@"device-model"] = [SKDefine getModel];
  45. headers[@"device-mac"] = [self getMacAddress];
  46. headers[@"device-type"] = @"3";
  47. //国内项目
  48. headers[@"X-System"] = @"IOS";
  49. headers[@"X-System-Version"] = iphoneSystemVersion;
  50. headers[@"X-Software-Version"] = iphoneAppVersion;
  51. headers[@"X-Manufacturer"] = @"Apple";
  52. headers[@"X-Time-Zone"] = timezone;
  53. headers[@"X-Timestamp"] = timestamp;
  54. headers[@"X-Request-Id"] = [NSString stringWithFormat:@"%@-%@", noncestr, timestamp];
  55. if (token && token.length > 0) {
  56. NSString* authorization = [NSString stringWithFormat:@"%@ %@", @"Bearer", token];
  57. headers[@"Authorization"] = authorization;
  58. }
  59. #ifdef SK_FUNCTION_ENCRYPT
  60. if (isEncrypt) {
  61. headers[@"token"] = token == nil ? @"" : token;
  62. if (param) {
  63. NSData* jsonData = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingFragmentsAllowed error:nil];
  64. NSString* data = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  65. data = [data URLEncode];
  66. NSString* sign = [NSString stringWithFormat:@"noncestr=%@&timestamp=%@&token=%@&data=%@", noncestr, timestamp, token, data];
  67. NSData *signData = [sign dataUsingEncoding:NSUTF8StringEncoding];
  68. NSString *signBase64 = [signData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
  69. sign = [signBase64 md5HexEncode];
  70. headers[@"sign"] = sign;
  71. }
  72. }
  73. #endif
  74. return headers;
  75. }
  76. + (NSData*)encryptionBody:(NSDictionary*)param isEncrypt:(BOOL)isEncrypt {
  77. #ifdef SK_FUNCTION_ENCRYPT
  78. if (isEncrypt) {
  79. NSString* key = KEY_AES;
  80. NSString* iv = KEY_AES;
  81. NSData* jsonData = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingFragmentsAllowed error:nil];
  82. NSData *jsonDataAES = [jsonData AES128EncryptWithKey:key gIv:iv];
  83. //NSString *signBase64 = [jsonDataAES base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
  84. return [jsonDataAES base64EncodedDataWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
  85. }
  86. #endif
  87. return [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:nil];
  88. }
  89. + (void)httpRequest:(NSDictionary*)param
  90. path:(NSString*)path
  91. httpURL:(NSString*)httpURL
  92. httpMethod:(NSString*)httpMethod
  93. onSuccess:(void(^)(NSDictionary* result))success
  94. onFailure:(void(^)(NSError* error))failure {
  95. //如果是服务器 >= 2,不加密
  96. NSInteger type = [ServerManager getServerType];
  97. BOOL isEncrypt = type >= 2 ? NO : YES;
  98. param = [self isGET:httpMethod] ? @{} : param;
  99. httpURL = [path isStartWithString:@"?"] ? [NSString stringWithFormat:@"%@%@", httpURL, path] : [NSString stringWithFormat:@"%@/%@", httpURL, path];
  100. [self httpRequest:param httpURL:httpURL httpMethod:httpMethod httpEncrypt:isEncrypt onSuccess:success onFailure:failure];
  101. }
  102. + (void)httpRequest:(NSDictionary*)param
  103. httpURL:(NSString*)httpURL
  104. httpMethod:(NSString*)httpMethod
  105. onSuccess:(void(^)(NSDictionary* result))success
  106. onFailure:(void(^)(NSError* error))failure {
  107. //如果是服务器 >= 2,不加密
  108. NSInteger type = [ServerManager getServerType];
  109. BOOL isEncrypt = type >= 2 ? NO : YES;
  110. [self httpRequest:param httpURL:httpURL httpMethod:httpMethod httpEncrypt:isEncrypt onSuccess:success onFailure:failure];
  111. }
  112. + (void)httpRequest:(NSDictionary*)param
  113. httpURL:(NSString*)httpURL
  114. httpMethod:(NSString*)httpMethod
  115. httpEncrypt:(BOOL)isEncrypt
  116. onSuccess:(void(^)(NSDictionary* result))success
  117. onFailure:(void(^)(NSError* error))failure {
  118. NSString* contentType = @"application/json";
  119. NSDictionary* header = [self setHeaders:param isEncrypt:isEncrypt contentType:contentType];
  120. NSData *body = [self encryptionBody:param isEncrypt:isEncrypt];
  121. [self httpRequest:param httpMethod:httpMethod httpURL:httpURL httpHeader:header body:body onSuccess:success onFailure:failure];
  122. }
  123. + (void)httpRequest:(NSDictionary*)param
  124. httpURL:(NSString*)httpURL
  125. httpEncrypt:(BOOL)isEncrypt
  126. fileData:(NSData*)fileData
  127. fileName:(NSString*)fileName
  128. mimeType:(NSString*)mimeType
  129. onSuccess:(void(^)(NSDictionary* result))success
  130. onFailure:(void(^)(NSError* error))failure {
  131. NSString* httpMethod = @"POST";
  132. NSString* contentType = @"multipart/form-data";
  133. NSDictionary* header = [self setHeaders:param isEncrypt:isEncrypt contentType:contentType];
  134. if (!httpMethod || [httpMethod isEqualToString:@""])
  135. return;
  136. if (!httpURL || [httpURL isEqualToString:@""])
  137. return;
  138. NSString* allUrl = [self joinHttpDomains:httpURL];
  139. HDNormalLog(([NSString stringWithFormat:@"------->>> 【%@】%@\n header:%@\n param:%@\n", httpMethod, allUrl, header, param]));
  140. AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
  141. manager.requestSerializer = [AFJSONRequestSerializer serializer];
  142. manager.requestSerializer.timeoutInterval = 15;
  143. for (NSString* key in header.allKeys) {
  144. [manager.requestSerializer setValue:header[key] forHTTPHeaderField:key];
  145. }
  146. manager.responseSerializer = [AFJSONResponseSerializer serializer];
  147. [manager.securityPolicy setAllowInvalidCertificates:YES];
  148. [manager.securityPolicy setValidatesDomainName:NO];
  149. [manager POST:allUrl parameters:param headers:@{} constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
  150. [formData appendPartWithFileData:fileData name:@"file" fileName:fileName mimeType:mimeType];
  151. } progress:^(NSProgress * _Nonnull uploadProgress) {
  152. } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  153. [ERequest httpCallback:httpMethod httpURL:allUrl response:task.response responseObject:responseObject error:nil onSuccess:success onFailure:failure];
  154. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  155. [ERequest httpCallback:httpMethod httpURL:allUrl response:task.response responseObject:nil error:error onSuccess:success onFailure:failure];
  156. }];
  157. }
  158. + (void)httpRequest:(NSDictionary*)param
  159. httpMethod:(NSString*)httpMethod
  160. httpURL:(NSString*)httpURL
  161. httpHeader:(NSDictionary*)header
  162. body:(NSData*)body
  163. onSuccess:(void(^)(NSDictionary* result))success
  164. onFailure:(void(^)(NSError* error))failure {
  165. if (!httpMethod || [httpMethod isEqualToString:@""])
  166. return;
  167. if (!httpURL || [httpURL isEqualToString:@""])
  168. return;
  169. NSString* allUrl = [self joinHttpDomains:httpURL];
  170. HDNormalLog(([NSString stringWithFormat:@"------->>> 【%@】%@\n header:%@\n param:%@\n", httpMethod, allUrl, header, param]));
  171. NSMutableURLRequest* request = [[AFHTTPRequestSerializer serializer] requestWithMethod:httpMethod URLString:allUrl parameters:param error:nil];
  172. [request setAllHTTPHeaderFields:header];
  173. [request setHTTPMethod:httpMethod];
  174. if (![self isGET:httpMethod]) {
  175. [request setHTTPBody:body];
  176. }
  177. //创建请求任务
  178. AFURLSessionManager* manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
  179. NSURLSessionDataTask *task = [manager dataTaskWithRequest:request uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
  180. } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
  181. } completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
  182. [ERequest httpCallback:httpMethod httpURL:allUrl response:response responseObject:responseObject error:error onSuccess:success onFailure:failure];
  183. }];
  184. [task resume];
  185. }
  186. + (void)downloadResource:(NSString*)httpURL localPath:(NSString*)localPath callback:(void(^)(BOOL isOK))callback {
  187. NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:httpURL]];
  188. NSURLSessionDownloadTask* task = [[AFHTTPSessionManager manager] downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
  189. } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
  190. return [NSURL fileURLWithPath:localPath];
  191. } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
  192. callback(error == nil);
  193. }];
  194. [task resume];
  195. }
  196. + (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 {
  197. //判断是否断网
  198. if (error && (error.code == -1009 || error.code == -1001)) {
  199. HDNormalLog(([NSString stringWithFormat:@"<<<------- 【%@】%@\n ########### %@ ########### \n", httpMethod, httpURL, error.userInfo[@"NSLocalizedDescription"]]));
  200. failure(error);
  201. } else {
  202. NSInteger statusCode = ((NSHTTPURLResponse *)response).statusCode;
  203. NSMutableDictionary* dic = [[NSMutableDictionary alloc] init];
  204. dic[@"code"] = @(statusCode);
  205. //200:请求成功
  206. if (statusCode == 200) {
  207. dic[@"data"] = responseObject;
  208. } else {
  209. [dic addEntriesFromDictionary:responseObject];
  210. }
  211. //判断是否Token过期
  212. if ([self isTokenExpiredWithResult:dic]) {
  213. [[NSNotificationCenter defaultCenter] postNotificationName:@"SK_TOKEN_EXPIRED" object:nil];
  214. }
  215. HDNormalLog(([NSString stringWithFormat:@"<<<------- 【%@】%@\n%@", httpMethod, httpURL, dic]));
  216. success(dic);
  217. }
  218. }
  219. + (void)successCallback:(NSString*)httpMethod httpURL:(NSString*)httpURL responseObject:(id)responseObject callback:(void(^)(NSDictionary *result))callback {
  220. HDNormalLog(([NSString stringWithFormat:@"<<<------- 【%@】%@\n%@", httpMethod, httpURL, responseObject]));
  221. //token过期
  222. if ([self isTokenExpiredWithResult:responseObject]) {
  223. [[NSNotificationCenter defaultCenter] postNotificationName:@"SK_TOKEN_EXPIRED" object:nil];
  224. }
  225. callback(responseObject);
  226. }
  227. + (void)failedCallback:(NSString*)httpMethod httpURL:(NSString*)httpURL responseObject:(id)responseObject error:(NSError*)error callback:(void(^)(NSError* error))callback {
  228. HDNormalLog(([NSString stringWithFormat:@"<<<------- 【%@】%@\n ########### %@ ########### \n", httpMethod, httpURL, error.userInfo[@"NSLocalizedDescription"]]));
  229. if (responseObject && [responseObject isKindOfClass:[NSDictionary class]]) {
  230. if ([self isTokenExpiredWithResult:responseObject]) {
  231. [[NSNotificationCenter defaultCenter] postNotificationName:@"SK_TOKEN_EXPIRED" object:nil];
  232. return;
  233. }
  234. }
  235. callback(error);
  236. }
  237. + (BOOL)isSuccessWithResult:(NSDictionary *)result {
  238. //200 成功
  239. NSInteger successCode = [result[@"code"] integerValue];
  240. if (successCode == 200) {
  241. return YES;
  242. }
  243. return NO;
  244. }
  245. + (BOOL)isTokenExpiredWithResult:(NSDictionary *)result {
  246. //Token过期,需要重新登录
  247. NSInteger successCode = [result[@"code"] integerValue];
  248. if (successCode == 405 || successCode == 401) {
  249. return YES;
  250. }
  251. return NO;
  252. }
  253. + (BOOL)isNeedWaitWithResult:(NSDictionary *)result {
  254. //406 中医提交数据,等待健康数据返回
  255. NSInteger successCode = [result[@"code"] integerValue];
  256. if (successCode == 406) {
  257. return YES;
  258. }
  259. return NO;
  260. }
  261. + (BOOL)isGET:(NSString*)httpMethod {
  262. return [self isStringEquel:httpMethod search:@"GET"];
  263. }
  264. + (BOOL)isStringEquel:(NSString*)value1 search:(NSString*)value2 {
  265. NSString* first = value1.trimString.uppercaseString.trimString;
  266. NSString* second = value2.trimString.uppercaseString.trimString;
  267. return [first isEqualToString:second];
  268. }
  269. + (NSString*)joinHttpDomains:(NSString*)httpURL {
  270. NSArray* info = [ServerManager getHttpDomains];
  271. NSString* url = [NSString stringWithFormat:@"%@%@", info[0], info[1]];
  272. if ([httpURL isEqualToString:@"/token/generate"]) {
  273. url = @"http://api.w303b.sikey.com.cn";
  274. }
  275. return [NSString stringWithFormat:@"%@%@",url, httpURL];
  276. }
  277. + (NSString*)joinQueryString:(NSDictionary*)dic {
  278. NSString* ret = @"";
  279. for (int i = 0; i < dic.allKeys.count; i++) {
  280. ret = [NSString stringWithFormat:@"%@%@=%@&", ret, dic.allKeys[i], dic.allValues[i]];
  281. }
  282. ret = [ret substringToIndex:ret.length - 1];
  283. return ret;
  284. }
  285. + (NSString*)getMacAddress {
  286. NSString* mac = [[NSUserDefaults standardUserDefaults] objectForKey:@"DeviceMacString"];
  287. return mac ? mac : @"";
  288. }
  289. + (NSString*)getToken {
  290. NSString* token = [[NSUserDefaults standardUserDefaults] objectForKey:@"sk_token"];
  291. return token ? token : @"";
  292. }
  293. + (NSString*)getTimezone {
  294. NSTimeInterval interval = [[NSTimeZone systemTimeZone] secondsFromGMTForDate:[NSDate date]];
  295. float timezone = interval / 3600;
  296. return [NSString stringWithFormat:@"%@%@%.1f", @"UTC", timezone > 0 ? @"+" : @"-", fabsf(timezone)];
  297. }
  298. + (NSString*)getTimezoneString {
  299. NSTimeZone* timeZone = [NSTimeZone systemTimeZone] ;///获取当前时区信息
  300. return timeZone.name;
  301. }
  302. @end