JXNetwork.m 17 KB

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