NetworkUtils.m 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. //
  2. // NetworkUtils.m
  3. // AntsContract
  4. //
  5. // Created by Ray on 12/26/16.
  6. // Copyright © 2016 United Software Applications, Inc. All rights reserved.
  7. //
  8. #import "NetworkUtils.h"
  9. #import "RAUtils.h"
  10. #import "Reachability.h"
  11. @implementation NetworkUtils
  12. //+(NSDictionary*) error_dict:(NSError*)error
  13. //{
  14. // if(error==nil)
  15. // return nil;
  16. // NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
  17. // [ret setValue:[NSString stringWithFormat:@"%d",error.code] forKey:@"error_code"];
  18. // [ret setValue:error.domain forKey:@"err_domain"];
  19. // [ret setValue:[error localizedDescription] forKey:@"err_message"];
  20. // // [ret setObject:error.userInfo forKey:@"user_info"];
  21. // return ret;
  22. //}
  23. +(bool) IsNetworkAvailable
  24. {
  25. if (([Reachability reachabilityForInternetConnection].currentReachabilityStatus == NotReachable) &&
  26. ([Reachability reachabilityForLocalWiFi].currentReachabilityStatus == NotReachable))
  27. return false;
  28. return true;
  29. }
  30. +(NSData*)get_json : (NSString*) url parameters:(NSMutableDictionary *) params file:(NSString*)file_path err_recorder:(NSString* )recorder_url result_handler:(resultBlock)resultBlock decrypt_handler:(decryptBlock)decryptBlock
  31. {
  32. int retry = 0;
  33. repeat:
  34. {
  35. // return [self fake_json:url];
  36. // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  37. //分界线的标识符
  38. NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
  39. //根据url初始化request
  40. NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
  41. cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
  42. timeoutInterval:JSON_TIMEOUT];
  43. //分界线 --AaB03x
  44. NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
  45. //结束符 AaB03x--
  46. NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
  47. //要上传的图片
  48. // UIImage *image=[params objectForKey:@"pic"];
  49. //得到图片的data
  50. NSData* data = [NSData dataWithContentsOfFile:file_path];
  51. //http body的字符串
  52. NSMutableString *body=[[NSMutableString alloc]init];
  53. // NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
  54. // [params setValue:@"handset_login" forKey:@"action"];
  55. // [headers setValue:[NSString stringWithFormat:@"%d",dataLength] forKey:@"Content-Length"];
  56. // [params setValue:appDelegate.sessionid forKey:@"sessionid"];
  57. // [params setValue:password forKey:@"password"];
  58. // [params setValue:[NSString stringWithFormat:@"%d",ver] forKey:@"auth_ver"];
  59. // [headers setValue:headQuerlString forKey:@"param"];
  60. //参数的集合的所有key的集合
  61. NSArray *keys= [params allKeys];
  62. DebugLog(@"================parms==================");
  63. //遍历keys
  64. for(int i=0;i<[keys count];i++)
  65. {
  66. //得到当前key
  67. NSString *key=[keys objectAtIndex:i];
  68. //如果key不是pic,说明value是字符类型,比如name:Boris
  69. if(![key isEqualToString:@"pic"])
  70. {
  71. //添加分界线,换行
  72. [body appendFormat:@"%@\r\n",MPboundary];
  73. //添加字段名称,换2行
  74. [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
  75. //添加字段的值
  76. [body appendFormat:@"%@\r\n",[params objectForKey:key]];
  77. DebugLog(@"parameter: key=%@ value=%@",key,[params objectForKey:key]);
  78. }
  79. }
  80. DebugLog(@"================parms==================");
  81. ////添加分界线,换行
  82. [body appendFormat:@"%@\r\n",MPboundary];
  83. //声明pic字段,文件名为boris.png
  84. NSString * file_format=[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"upfile\"; filename=\"%@\"\r\n", [file_path lastPathComponent]];
  85. [body appendFormat:@"%@", file_format];
  86. //声明上传文件的格式
  87. [body appendFormat:@"Content-Type: application/zip\r\n\r\n"];
  88. //声明结束符:--AaB03x--
  89. NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
  90. //声明myRequestData,用来放入http body
  91. NSMutableData *myRequestData=[NSMutableData data];
  92. //将body字符串转化为UTF8格式的二进制
  93. [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
  94. //将image的data加入
  95. [myRequestData appendData:data];
  96. //加入结束符--AaB03x--
  97. [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
  98. //设置HTTPHeader中Content-Type的值
  99. NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
  100. //设置HTTPHeader
  101. [request setValue:content forHTTPHeaderField:@"Content-Type"];
  102. // 关闭keep alive
  103. [request setValue:@"close" forHTTPHeaderField:@"Connection"];
  104. //设置Content-Length
  105. [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
  106. //设置http body
  107. [request setHTTPBody:myRequestData];
  108. //http method
  109. [request setHTTPMethod:@"POST"];
  110. NSHTTPURLResponse* urlResponse = nil;
  111. NSError *error = nil;
  112. NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
  113. DebugLog(@"url: %@",url);
  114. DebugLog(@"response: %@",[NSHTTPURLResponse localizedStringForStatusCode:urlResponse.statusCode]);
  115. if (responseData==nil) {
  116. // DebugLog(@"response error:%@", [error localizedDescription]);
  117. NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
  118. //#define RESULT_FALSE 0
  119. //#define RESULT_TRUE 2
  120. //#define RESULT_NET_ERROR -3
  121. //#define RESULT_NET_NOTAVAILABLE -4
  122. //#define RESULT_ERROR -5
  123. //#define RESULT_LOCALFILE_ERROR -7
  124. //#define RESULT_USERAUTH_ERROR -9
  125. //#define RESULT_UPDATE_USERAUTH_ERROR -11
  126. //#define RESULT_SESSION_EXPIRED -13
  127. //#define RESULT_VER_LOW
  128. // NSString * moreinfo = error.description ;
  129. NSString* err_msg = [error localizedDescription];
  130. //-----------------retry 3 times for error code -1005------------------------
  131. if(error.code==-1005&&retry<3)
  132. {
  133. retry++;
  134. goto repeat;
  135. }
  136. //-----------------end retry 3 times for error code -1005------------------------
  137. NSDictionary* error_json = [RAUtils error_dict:error];
  138. [ret setObject:error_json forKey:@"err_obj"];
  139. NSString* resp_msg= nil;
  140. if(err_msg.length==0)
  141. {
  142. err_msg =[NSHTTPURLResponse localizedStringForStatusCode:urlResponse.statusCode];
  143. resp_msg = err_msg;
  144. }
  145. [ret setValue:[NSString stringWithFormat:@"%d",RESULT_NET_ERROR] forKey:@"result"];
  146. [ret setValue:err_msg forKey:@"err_msg"];
  147. [ret setValue:resp_msg forKey:@"resp_msg"];
  148. [ret setValue:[NSString stringWithFormat:@"%ld",(long)urlResponse.statusCode] forKey:@"resp_code"];
  149. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ret
  150. options:0
  151. error:nil];
  152. if(![url isEqualToString:recorder_url])
  153. {
  154. [self err_log:[RAUtils base64en:[RAUtils dict2string:params]] result:[RAUtils base64en:[RAUtils dict2string:ret]] module:url code:RESULT_NET_ERROR];
  155. }
  156. return jsonData;
  157. }
  158. else
  159. {
  160. // NSString* err_msg = [error localizedDescription];
  161. NSMutableString *str = [[NSMutableString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
  162. DebugLog(@"data string: %@",str);
  163. NSError *error1 = nil;
  164. NSMutableDictionary* jsobj = [[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error1] mutableCopy];
  165. if(jsobj==nil)// 服务器返回不是json
  166. {
  167. jsobj=[[NSMutableDictionary alloc] init];
  168. [jsobj setValue:@"1" forKey:@"result"];
  169. }
  170. if([jsobj[@"encrypt"] boolValue]==true)
  171. {
  172. jsobj = decryptBlock(jsobj);
  173. }
  174. jsobj = resultBlock(jsobj);
  175. int result=[[jsobj valueForKey:@"result"] intValue];
  176. if(![url isEqualToString:recorder_url]&&/*![url isEqualToString:URL_DOWNLOAD_OFFLINE]&&*/result!=2&&result!=99)
  177. {
  178. [self err_log:[RAUtils base64en:[RAUtils dict2string:params]] result:[RAUtils base64en:str] module:url code:result];
  179. }
  180. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsobj
  181. options:0
  182. error:nil];
  183. return jsonData;
  184. }
  185. return responseData;
  186. }
  187. }
  188. @end