JXNetwork.m 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. //
  2. // JXNetwork.m
  3. // JXNetwork
  4. //
  5. // Created by Hao Tan on 11-11-19.
  6. // Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
  7. //
  8. #import "JXNetwork.h"
  9. #import <CommonCrypto/CommonDigest.h>
  10. #import <CommonCrypto/CommonHMAC.h>
  11. //#import "NSDataEx.h"
  12. //#define MULTIPART @"multipart/form-data; boundary=------------0x0x0x0x0x0x0x0x"
  13. //#define MULTIPART @"multipart/form-data"
  14. //#define MULTIPART @"application/x-www-form-urlencoded"
  15. #define UploadDefultTimeout 60
  16. #define NormalDefultTimeout 15
  17. @interface JXNetwork ()
  18. @property (nonatomic, strong) NSMutableDictionary *params;
  19. @property (nonatomic, strong) NSMutableDictionary *uploadDataDic;
  20. @property (nonatomic, strong) AFHTTPSessionManager *httpManager;
  21. @property (nonatomic, assign) BOOL isUpload;
  22. @end
  23. @implementation JXNetwork
  24. @synthesize action;
  25. @synthesize toView;
  26. @synthesize downloadFile;
  27. static AFHTTPSessionManager *afManager;
  28. -(AFHTTPSessionManager *)sharedHttpSessionManager {
  29. static dispatch_once_t onceToken;
  30. dispatch_once(&onceToken, ^{
  31. afManager = [AFHTTPSessionManager manager];
  32. afManager.requestSerializer.timeoutInterval = 10.0;
  33. // afManager.securityPolicy = [self customSecurityPolicy];
  34. });
  35. return afManager;
  36. }
  37. /**** SSL Pinning ****/
  38. - (AFSecurityPolicy*)customSecurityPolicy {
  39. NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"server" ofType:@"cer"];
  40. NSData *certData = [NSData dataWithContentsOfFile:cerPath];
  41. AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
  42. [securityPolicy setAllowInvalidCertificates:YES];
  43. NSSet *set = [NSSet setWithObjects:certData, nil];
  44. [securityPolicy setPinnedCertificates:set];
  45. /**** SSL Pinning ****/
  46. return securityPolicy;
  47. }
  48. - (id) init {
  49. if (self = [super init]) {
  50. self.params = [NSMutableDictionary dictionary];
  51. self.uploadDataDic = [NSMutableDictionary dictionary];
  52. self.httpManager = [self sharedHttpSessionManager];
  53. self.httpManager.requestSerializer = [AFHTTPRequestSerializer serializer];// 请求
  54. self.httpManager.responseSerializer = [AFHTTPResponseSerializer serializer];// 响应
  55. // self.httpManager.requestSerializer.timeoutInterval = jx_connect_timeout;
  56. }
  57. return self;
  58. }
  59. -(void)dealloc{
  60. self.action = nil;
  61. self.toView = nil;
  62. // self.userInfo = nil;
  63. self.delegate = nil;
  64. self.url = nil;
  65. self.param = nil;
  66. self.params = nil;
  67. self.uploadDataDic = nil;
  68. self.downloadFile = nil;
  69. // [self.httpManager release];
  70. //
  71. // [super dealloc];
  72. }
  73. -(BOOL)isImage{
  74. return [action rangeOfString:@".jpg"].location != NSNotFound || [action rangeOfString:@".png"].location != NSNotFound || [action rangeOfString:@".gif"].location != NSNotFound;
  75. }
  76. -(BOOL)isVideo{
  77. NSString* s = [action lowercaseString];
  78. BOOL b = [s rangeOfString:@".mp4"].location != NSNotFound
  79. || [s rangeOfString:@".qt"].location != NSNotFound
  80. || [s rangeOfString:@".mpg"].location != NSNotFound
  81. || [s rangeOfString:@".mov"].location != NSNotFound
  82. || [s rangeOfString:@".avi"].location != NSNotFound;
  83. return b;
  84. }
  85. -(BOOL)isAudio{
  86. NSString* s = [action lowercaseString];
  87. return [s rangeOfString:@".mp3"].location != NSNotFound || [s rangeOfString:@".amr"].location != NSNotFound|| [s rangeOfString:@".wav"].location != NSNotFound;
  88. }
  89. -(void)go{
  90. if([self isImage] || [self isVideo] || [self isAudio]) {
  91. self.isUpload = NO;
  92. [self downloadRequestData];
  93. }else {
  94. if (self.uploadDataDic.count > 0) {
  95. self.isUpload = YES;
  96. [self getSecret];
  97. [self upLoadRequestData];
  98. }else {
  99. self.isUpload = NO;
  100. [self getSecret];
  101. [self normalRequestData];
  102. }
  103. }
  104. }
  105. // 普通网络请求
  106. - (void) normalRequestData {
  107. if (self.timeout && self.timeout > 0) {
  108. self.httpManager.requestSerializer.timeoutInterval = self.timeout;
  109. }else {
  110. self.httpManager.requestSerializer.timeoutInterval = NormalDefultTimeout;
  111. }
  112. NSMutableString *urlStr = [NSMutableString string];
  113. if (YES) {
  114. NSRange range = [self.url rangeOfString:@"?"];
  115. if (range.location == NSNotFound) {
  116. urlStr = [NSMutableString stringWithFormat:@"%@?",self.url];
  117. }else{
  118. urlStr = [self.url mutableCopy];
  119. }
  120. for (NSString *key in self.params.allKeys) {
  121. NSString *str = [NSString stringWithFormat:@"&%@=%@",key, self.params[key]];
  122. [urlStr appendString:str];
  123. }
  124. // NSLog(@"urlStr = %@", urlStr);
  125. }
  126. urlStr = [[urlStr stringByReplacingOccurrencesOfString:@" " withString:@""] copy];
  127. if ([self.action isEqualToString:act_Config]) {
  128. [self.httpManager GET:urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
  129. } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  130. // 转码
  131. NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  132. self.responseData = string;
  133. NSLog(@"requestSuccess");
  134. if ([self.delegate respondsToSelector:@selector(requestSuccess:)]) {
  135. [self.delegate requestSuccess:self];
  136. }
  137. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  138. NSLog(@"%@:requestFailed",self.url);
  139. self.error = error;
  140. if ([self.delegate respondsToSelector:@selector(requestError:)]) {
  141. [self.delegate requestError:self];
  142. }
  143. }];
  144. }else {
  145. [self.httpManager POST:self.url parameters:self.params progress:^(NSProgress * _Nonnull downloadProgress) {
  146. } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  147. // 转码
  148. NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  149. self.responseData = string;
  150. NSLog(@"requestSuccess");
  151. if ([self.delegate respondsToSelector:@selector(requestSuccess:)]) {
  152. [self.delegate requestSuccess:self];
  153. }
  154. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  155. NSLog(@"%@:requestFailed",self.url);
  156. self.error = error;
  157. if ([self.delegate respondsToSelector:@selector(requestError:)]) {
  158. [self.delegate requestError:self];
  159. }
  160. }];
  161. }
  162. }
  163. // 上传
  164. - (void) upLoadRequestData{
  165. if (self.timeout && self.timeout > 0) {
  166. self.httpManager.requestSerializer.timeoutInterval = self.timeout;
  167. }else {
  168. NSUInteger dataLength = 0;
  169. for (NSString *key in self.uploadDataDic.allKeys) {
  170. NSData *data = self.uploadDataDic[key];
  171. dataLength = dataLength + data.length;
  172. }
  173. NSUInteger timeOut = dataLength / 1024 / 20;
  174. if (timeOut > UploadDefultTimeout) {
  175. self.httpManager.requestSerializer.timeoutInterval = timeOut;
  176. }else {
  177. self.httpManager.requestSerializer.timeoutInterval = UploadDefultTimeout;
  178. }
  179. }
  180. self.httpManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
  181. @"text/html",
  182. @"image/jpeg",
  183. @"image/png",
  184. @"image/gif",
  185. @"application/octet-stream",
  186. @"text/json",
  187. @"video/mp4",
  188. @"video/quicktime",
  189. nil];
  190. //上传图片/文字,只能同POST
  191. [self.httpManager POST:self.url parameters:self.params constructingBodyWithBlock:^(id _Nonnull formData) {
  192. // 上传文件
  193. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  194. formatter.dateFormat = @"yyyyMMddHHmmss";
  195. for (NSString *key in self.uploadDataDic.allKeys) {
  196. NSData *data = self.uploadDataDic[key];
  197. NSString *mimeType = [self getUploadDataMimeType:key];
  198. [formData appendPartWithFileData:data name:key fileName:key mimeType:mimeType];
  199. }
  200. } progress:^(NSProgress * _Nonnull uploadProgress) {
  201. // NSLog(@"---------- uploadProgress = %@",uploadProgress);
  202. // if (self.messageId.length > 0) {
  203. // [g_notify postNotificationName:kUploadFileProgressNotifaction object:@{@"uploadProgress":uploadProgress,@"file":self.messageId}];
  204. // }
  205. } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  206. NSLog(@"responseObject = %@, task = %@",responseObject,task);
  207. // 转码
  208. NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  209. self.responseData = string;
  210. NSLog(@"requestSuccess");
  211. if ([self.delegate respondsToSelector:@selector(requestSuccess:)]) {
  212. [self.delegate requestSuccess:self];
  213. }
  214. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  215. NSLog(@"error = %@",error);
  216. self.error = error;
  217. if ([self.delegate respondsToSelector:@selector(requestError:)]) {
  218. [self.delegate requestError:self];
  219. }
  220. }];
  221. }
  222. // 下载
  223. - (void) downloadRequestData {
  224. NSURLSessionConfiguration *conf = [NSURLSessionConfiguration defaultSessionConfiguration];
  225. AFURLSessionManager *urlManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:conf];
  226. NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.action]];
  227. NSURLSessionDownloadTask *task = [urlManager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
  228. // NSLog(@"文件下载进度:%lld/%lld",downloadProgress.completedUnitCount,downloadProgress.totalUnitCount);
  229. } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
  230. NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
  231. return [documentsDirectoryURL URLByAppendingPathComponent:[targetPath lastPathComponent]];
  232. } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
  233. if (error) {
  234. NSLog(@"error ---- %@", error);
  235. self.error = error;
  236. if ([self.delegate respondsToSelector:@selector(requestError:)]) {
  237. [self.delegate requestError:self];
  238. }
  239. }else {
  240. NSLog(@"downloadSuccess");
  241. NSString *downloadPath = [NSString stringWithFormat:@"%@", filePath];
  242. NSData *data = [NSData dataWithContentsOfURL:filePath];
  243. self.responseData = data;
  244. if ([self.delegate respondsToSelector:@selector(requestSuccess:)]) {
  245. [self.delegate requestSuccess:self];
  246. }
  247. [[NSFileManager defaultManager] removeItemAtPath:downloadPath error:nil];
  248. }
  249. }];
  250. [task resume];
  251. }
  252. // 返回上传数据类型
  253. - (NSString *) getUploadDataMimeType:(NSString *) key {
  254. NSString *mimeType = nil;
  255. key = [key lowercaseString];
  256. if ([key rangeOfString:@".jpg"].location != NSNotFound || [key rangeOfString:@"image"].location != NSNotFound) {
  257. mimeType = @"image/jpeg";
  258. }else if ([key rangeOfString:@".png"].location != NSNotFound) {
  259. mimeType = @"image/png";
  260. }else if ([key rangeOfString:@".mp3"].location != NSNotFound) {
  261. mimeType = @"audio/mpeg";
  262. }else if ([key rangeOfString:@".qt"].location != NSNotFound) {
  263. mimeType = @"video/quicktime";
  264. }else if ([key rangeOfString:@".mp4"].location != NSNotFound) {
  265. mimeType = @"video/mp4";
  266. }else if ([key rangeOfString:@".amr"].location != NSNotFound) {
  267. mimeType = @"audio/amr";
  268. }else if ([key rangeOfString:@".gif"].location != NSNotFound) {
  269. mimeType = @"image/gif";
  270. }else if ([key rangeOfString:@".mov"].location != NSNotFound) {
  271. mimeType = @"video/quicktime";
  272. }else if ([key rangeOfString:@".wav"].location != NSNotFound) {
  273. mimeType = @"audio/wav";
  274. }else {
  275. mimeType = @"";
  276. }
  277. return mimeType;
  278. }
  279. - (void)stop{
  280. AFHTTPSessionManager *manager = [self sharedHttpSessionManager];
  281. [manager.operationQueue cancelAllOperations];
  282. }
  283. - (void)setData:(NSData *)data forKey:(NSString *)key messageId:(NSString *)messageId
  284. {
  285. if(data==nil)
  286. return;
  287. [self.uploadDataDic setObject:data forKey:key];
  288. self.messageId = messageId;
  289. self.uploadDataSize = data.length;
  290. }
  291. - (void)setPostValue:(id <NSObject>)value forKey:(NSString *)key
  292. {
  293. if(value==nil)
  294. return;
  295. [self.params setObject:value forKey:key];
  296. }
  297. //// 接口加密
  298. //- (NSString *)getSecret {
  299. // long time = (long)[[NSDate date] timeIntervalSince1970];
  300. // long timeDifference = [[share_defaults objectForKey:kShare_timeDifference] longValue];
  301. // time = (time *1000 + timeDifference)/1000;
  302. // [self setPostValue:[NSString stringWithFormat:@"%ld",time] forKey:@"time"];
  303. //
  304. // NSString *secret;
  305. //
  306. // NSMutableString *str1 = [NSMutableString string];
  307. // [str1 appendString:APIKEY];
  308. // [str1 appendString:[NSString stringWithFormat:@"%ld",time]];
  309. //
  310. // [str1 appendString:[[JXHttpRequet shareInstance] userId]];
  311. // [str1 appendString:[[JXHttpRequet shareInstance] access_token]];
  312. // secret = [self getMd5:str1];
  313. //
  314. // [self setPostValue:secret forKey:@"secret"];
  315. //
  316. // return secret;
  317. //}
  318. // 接口加密
  319. - (NSString *)getSecret {
  320. long time = (long)[[NSDate date] timeIntervalSince1970];
  321. time = (time *1000 + [JXHttpRequet shareInstance].timeDifference);
  322. NSString *salt = [NSString stringWithFormat:@"%ld",time];
  323. if (self.params[@"salt"]) {
  324. salt = self.params[@"salt"];
  325. }
  326. NSMutableString *macStr = [NSMutableString string];
  327. [macStr appendString:APIKEY];
  328. [macStr appendString:[JXHttpRequet shareInstance].userId];
  329. [macStr appendString:[JXHttpRequet shareInstance].access_token];
  330. NSString *paramStr = [self getParamStr];
  331. [macStr appendString:paramStr];
  332. [macStr appendString:salt];
  333. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:[JXHttpRequet shareInstance].httpKey options:NSDataBase64DecodingIgnoreUnknownCharacters];
  334. NSData *macData = [self getHMACMD5:[macStr dataUsingEncoding:NSUTF8StringEncoding] key:keyData];
  335. NSString *secret = [macData base64EncodedStringWithOptions:0];
  336. if (!self.params[@"salt"]) {
  337. [self setPostValue:salt forKey:@"salt"];
  338. }
  339. [self setPostValue:secret forKey:@"secret"];
  340. return secret;
  341. }
  342. - (NSString *)getParamStr {
  343. NSMutableString *paramStr = [NSMutableString string];
  344. NSArray *keys = [[self.params allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
  345. for (NSInteger i = 0; i < keys.count; i ++) {
  346. NSString *key = keys[i];
  347. if ([key isEqualToString:@"salt"]) {
  348. continue;
  349. }
  350. if ([key isEqualToString:@"access_token"]) {
  351. continue;
  352. }
  353. NSString *value = self.params[key];
  354. if ([self.params[key] isKindOfClass:[NSNumber class]]) {
  355. NSNumber *num = self.params[key];
  356. value = [num stringValue];
  357. }
  358. [paramStr appendString:value];
  359. [self.params setObject:value forKey:key];
  360. }
  361. return paramStr;
  362. }
  363. // 获取mac值(HMACMD5算法)
  364. - (NSData *)getHMACMD5:(NSData *)data key:(NSData *)keyData {
  365. size_t dataLength = data.length;
  366. NSData *keys = keyData;
  367. size_t keyLength = keys.length;
  368. unsigned char result[CC_MD5_DIGEST_LENGTH];
  369. CCHmac(kCCHmacAlgMD5, [keys bytes], keyLength, [data bytes], dataLength, result);
  370. for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i ++) {
  371. printf("%d ",result[i]);
  372. }
  373. printf("\n-------%s-------\n",result);
  374. //这里需要将result 转base64编码,再传回去
  375. NSData *data1 = [[NSData alloc] initWithBytes:result length:sizeof(result)];
  376. // NSString *base64 = [data1 base64EncodedStringWithOptions:0];
  377. return data1;
  378. }
  379. void CCHmac(CCHmacAlgorithm algorithm,/* kCCHmacAlgSHA1, kCCHmacAlgMD5 */
  380. const void *key,
  381. size_t keyLength,/* length of key in bytes */
  382. const void *data,
  383. size_t dataLength,/* length of data in bytes */
  384. void *macOut)/* MAC written here */
  385. __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_2_0);
  386. - (NSString *)getMd5:(NSString *)str
  387. {
  388. const char *cStr = [str UTF8String];
  389. unsigned char result[16];
  390. CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
  391. return [NSString stringWithFormat:
  392. @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
  393. result[0], result[1], result[2], result[3],
  394. result[4], result[5], result[6], result[7],
  395. result[8], result[9], result[10], result[11],
  396. result[12], result[13], result[14], result[15]
  397. ];
  398. }
  399. @end