NetworkManager.m 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. //
  2. // NetworkManager.m
  3. // LNManager
  4. //
  5. // Created by EchoShacolee on 2017/4/6.
  6. // Copyright © 2017年 lee. All rights reserved.
  7. //
  8. #import "NetworkManager.h"
  9. #import "NetHeader.h"
  10. #import <AFNetworking.h>
  11. #import <RealReachability/RealReachability.h>
  12. #import "NSString+ex.h"
  13. #import <MBProgressHUD.h>
  14. @implementation NetworkManager
  15. + (BOOL) connectedToNetWork{
  16. [GLobalRealReachability startNotifier];
  17. ReachabilityStatus status = [GLobalRealReachability currentReachabilityStatus];
  18. [GLobalRealReachability stopNotifier];
  19. return status ? YES : NO;
  20. }
  21. + (void)requestWithMethod:(NSString *)method
  22. parameters:(id)parameters
  23. type:(HttpRequestType)type
  24. handler:(GetDataHandler)handler;{
  25. AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
  26. manager.requestSerializer = [AFJSONRequestSerializer serializer];
  27. manager.responseSerializer = [AFHTTPResponseSerializer serializer];
  28. manager.requestSerializer.timeoutInterval = 15;
  29. // manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript", nil];
  30. //生成请求加密后的url
  31. NSString *URLString = [NetworkManager getURLWithDict:parameters urlPre:method];
  32. switch (type) {
  33. case HttpRequestTypeGet:
  34. {
  35. [manager GET:URLString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  36. if (handler) {
  37. if (responseObject == nil) {
  38. handler(nil,@"无数据");
  39. return;
  40. }
  41. NSError * error;
  42. NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options: NSJSONReadingMutableContainers error:&error];
  43. if (error) {
  44. handler(nil,@"数据解析异常");
  45. // NSLog(@"数据解析异常-%@<%@>error:%@",parameters,method,error);
  46. }else{
  47. handler(dic,nil);
  48. // NSLog(@"%@<%@>success:%@",parameters,method,dic);
  49. }
  50. }
  51. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  52. if (handler) {
  53. if ([error.localizedDescription isEqualToString:@"The request timed out."]) {
  54. handler(nil,@"请求超时");
  55. }else{
  56. handler(nil,@"请求失败");
  57. // NSLog(@"post请求失败-%@\n%ld\n%@\n%@\n%@\n本地恢复建议%@\n获取恢复建议%@",
  58. // parameters,
  59. // (long)error.code,
  60. // error.localizedDescription,
  61. // error.userInfo[@"NSErrorFailingURLStringKey"],
  62. // error.localizedFailureReason,
  63. // error.localizedRecoveryOptions,
  64. // error.localizedRecoverySuggestion);
  65. }
  66. }
  67. }];
  68. }
  69. break;
  70. case HttpRequestTypePost:
  71. {
  72. [manager POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  73. if (handler) {
  74. if (responseObject == nil) {
  75. handler(nil,@"无数据");
  76. return;
  77. }
  78. NSError * error;
  79. NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options: NSJSONReadingMutableContainers error:&error];
  80. if (error) {
  81. handler(nil,@"数据解析异常");
  82. NSLog(@"数据解析异常-%@<%@>error:%@",parameters,URLString,error);
  83. }else{
  84. handler(dic,nil);
  85. NSLog(@"%@<%@>success:%@",parameters,URLString,dic);
  86. }
  87. }
  88. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  89. if (handler) {
  90. if ([error.localizedDescription isEqualToString:@"The request timed out."]) {
  91. handler(nil,@"请求超时");
  92. }else{
  93. handler(nil,@"请求失败");
  94. NSLog(@"post请求失败-%@\n%ld\n%@\n%@\n%@\n本地恢复建议%@\n获取恢复建议%@",
  95. parameters,
  96. (long)error.code,
  97. error.localizedDescription,
  98. error.userInfo[@"NSErrorFailingURLKey"],
  99. error.localizedFailureReason,
  100. error.localizedRecoveryOptions,
  101. error.localizedRecoverySuggestion);
  102. }
  103. }
  104. }];
  105. }
  106. break;
  107. }
  108. }
  109. //生成带有签名的URL
  110. + (NSString *)getURLWithDict:(NSDictionary *)dic urlPre:(NSString *)urlP
  111. {
  112. NSString *httpUrl = defaultHttp;
  113. if (!isOfficial) {
  114. httpUrl = TestHttp;
  115. }
  116. NSString *urlDefault = defaultHttpUrl;
  117. NSTimeInterval timeI = [[NSDate date] timeIntervalSince1970] * 1000;//获取时间戳 单位:s *1000毫秒
  118. NSString *urlS = @"";
  119. if (dic == nil) {
  120. urlS = [NSString stringWithFormat:@"%@%@%@?ts=%@&user=ios&v=jsjp",httpUrl,urlDefault,urlP,[NSString stringWithFormat:@"%.0f",timeI]];
  121. }else{
  122. //添加key字段
  123. NSMutableString *contentString = [NSMutableString stringWithString:[self getSignStringWithDictionary:dic]];
  124. [contentString appendFormat:@"key=%@", [NSString stringWithFormat:@"%.0f",timeI]];
  125. urlS = [NSString stringWithFormat:@"%@%@%@?ts=%@&sign=%@&user=ios&v=jsjp",httpUrl,urlDefault,urlP,[NSString stringWithFormat:@"%.0f",timeI],[[contentString md5Encrypt] uppercaseString]];
  126. }
  127. return urlS;
  128. }
  129. + (NSString *)getSignStringWithDictionary:(NSDictionary *)dic
  130. {
  131. NSMutableString *contentString =[NSMutableString string];
  132. NSDictionary* dict = [NSDictionary dictionaryWithDictionary:dic];
  133. NSArray *keys = [dict allKeys];
  134. //按字母顺序排序
  135. NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  136. return [obj1 compare:obj2 options:NSNumericSearch];
  137. }];
  138. //拼接字符串
  139. for (NSString *categoryId in sortedArray) {
  140. if (![categoryId isEqualToString:@"sign"] && ![categoryId isEqualToString:@"timestamp"]){
  141. if([categoryId isEqualToString:@"biz_content"]){
  142. NSError *error = nil;
  143. NSDictionary* bizDict = [dict objectForKey:@"biz_content"];
  144. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:bizDict options:NSJSONWritingPrettyPrinted error: &error];
  145. NSMutableData *tempJsonData = [NSMutableData dataWithData:jsonData];
  146. NSString* jsonString1 = [[NSString alloc] initWithData:tempJsonData encoding:NSUTF8StringEncoding];
  147. NSString *jsonString2 = [jsonString1 stringByReplacingOccurrencesOfString:@" : " withString:@":"];
  148. [contentString appendFormat:@"biz_content=%@&",jsonString2];
  149. }else{
  150. [contentString appendFormat:@"%@=%@&", categoryId, [dict valueForKey:categoryId]];
  151. }
  152. }
  153. }
  154. return contentString;
  155. }
  156. @end