NetworkUtils.m 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818
  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. #import "RANetworkTaskDelegate.h"
  12. #define BOUNDARY @"AaB03x"
  13. @implementation NetworkUtils
  14. //+(NSDictionary*) error_dict:(NSError*)error
  15. //{
  16. // if(error==nil)
  17. // return nil;
  18. // NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
  19. // [ret setValue:[NSString stringWithFormat:@"%d",error.code] forKey:@"error_code"];
  20. // [ret setValue:error.domain forKey:@"err_domain"];
  21. // [ret setValue:[error localizedDescription] forKey:@"err_message"];
  22. // // [ret setObject:error.userInfo forKey:@"user_info"];
  23. // return ret;
  24. //}
  25. +(bool) IsNetworkAvailable
  26. {
  27. if (([Reachability reachabilityForInternetConnection].currentReachabilityStatus == NotReachable)
  28. /* &&
  29. ([Reachability reachabilityForLocalWiFi].currentReachabilityStatus == NotReachable)*/)
  30. return false;
  31. return true;
  32. }
  33. +(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
  34. {
  35. int retry = 0;
  36. repeat:
  37. {
  38. // return [self fake_json:url];
  39. // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  40. //分界线的标识符
  41. NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
  42. //根据url初始化request
  43. NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
  44. cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
  45. timeoutInterval:JSON_TIMEOUT];
  46. //分界线 --AaB03x
  47. NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
  48. //结束符 AaB03x--
  49. NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
  50. //要上传的图片
  51. // UIImage *image=[params objectForKey:@"pic"];
  52. //得到图片的data
  53. NSData* data = [NSData dataWithContentsOfFile:file_path];
  54. //http body的字符串
  55. NSMutableString *body=[[NSMutableString alloc]init];
  56. // NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
  57. // [params setValue:@"handset_login" forKey:@"action"];
  58. // [headers setValue:[NSString stringWithFormat:@"%d",dataLength] forKey:@"Content-Length"];
  59. // [params setValue:appDelegate.sessionid forKey:@"sessionid"];
  60. // [params setValue:password forKey:@"password"];
  61. // [params setValue:[NSString stringWithFormat:@"%d",ver] forKey:@"auth_ver"];
  62. // [headers setValue:headQuerlString forKey:@"param"];
  63. //参数的集合的所有key的集合
  64. NSArray *keys= [params allKeys];
  65. DebugLog(@"================parms==================");
  66. //遍历keys
  67. for(int i=0;i<[keys count];i++)
  68. {
  69. //得到当前key
  70. NSString *key=[keys objectAtIndex:i];
  71. //如果key不是pic,说明value是字符类型,比如name:Boris
  72. if(![key isEqualToString:@"pic"])
  73. {
  74. //添加分界线,换行
  75. [body appendFormat:@"%@\r\n",MPboundary];
  76. //添加字段名称,换2行
  77. [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
  78. //添加字段的值
  79. [body appendFormat:@"%@\r\n",[params objectForKey:key]];
  80. DebugLog(@"parameter: key=%@ value=%@",key,[params objectForKey:key]);
  81. }
  82. }
  83. DebugLog(@"================parms==================");
  84. ////添加分界线,换行
  85. [body appendFormat:@"%@\r\n",MPboundary];
  86. //声明pic字段,文件名为boris.png
  87. NSString * file_format=[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"upfile\"; filename=\"%@\"\r\n", [file_path lastPathComponent]];
  88. [body appendFormat:@"%@", file_format];
  89. //声明上传文件的格式
  90. [body appendFormat:@"Content-Type: application/zip\r\n\r\n"];
  91. //声明结束符:--AaB03x--
  92. NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
  93. //声明myRequestData,用来放入http body
  94. NSMutableData *myRequestData=[NSMutableData data];
  95. //将body字符串转化为UTF8格式的二进制
  96. [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
  97. //将image的data加入
  98. [myRequestData appendData:data];
  99. //加入结束符--AaB03x--
  100. [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
  101. //设置HTTPHeader中Content-Type的值
  102. NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
  103. //设置HTTPHeader
  104. [request setValue:content forHTTPHeaderField:@"Content-Type"];
  105. [request setValue:@"multipart/form-data" forHTTPHeaderField:@"enctype"];
  106. // 关闭keep alive
  107. [request setValue:@"close" forHTTPHeaderField:@"Connection"];
  108. //设置Content-Length
  109. [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
  110. //设置http body
  111. [request setHTTPBody:myRequestData];
  112. //http method
  113. [request setHTTPMethod:@"POST"];
  114. NSLog([[NSString alloc] initWithData:myRequestData encoding:NSUTF8StringEncoding]);
  115. NSHTTPURLResponse* urlResponse = nil;
  116. NSError *error = nil;
  117. NSLog(@"begin request %@",url);
  118. NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
  119. DebugLog(@"url: %@",url);
  120. DebugLog(@"response: %@",[NSHTTPURLResponse localizedStringForStatusCode:urlResponse.statusCode]);
  121. NSLog(@"get response");
  122. if (responseData==nil) {
  123. // DebugLog(@"response error:%@", [error localizedDescription]);
  124. NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
  125. //#define RESULT_FALSE 0
  126. //#define RESULT_TRUE 2
  127. //#define RESULT_NET_ERROR -3
  128. //#define RESULT_NET_NOTAVAILABLE -4
  129. //#define RESULT_ERROR -5
  130. //#define RESULT_LOCALFILE_ERROR -7
  131. //#define RESULT_USERAUTH_ERROR -9
  132. //#define RESULT_UPDATE_USERAUTH_ERROR -11
  133. //#define RESULT_SESSION_EXPIRED -13
  134. //#define RESULT_VER_LOW
  135. // NSString * moreinfo = error.description ;
  136. NSString* err_msg = [error localizedDescription];
  137. //-----------------retry 3 times for error code -1005------------------------
  138. if(error.code==-1005&&retry<3)
  139. {
  140. retry++;
  141. goto repeat;
  142. }
  143. //-----------------end retry 3 times for error code -1005------------------------
  144. NSDictionary* error_json = [RAUtils error_dict:error];
  145. [ret setObject:error_json forKey:@"err_obj"];
  146. NSString* resp_msg= nil;
  147. if(err_msg.length==0)
  148. {
  149. err_msg =[NSHTTPURLResponse localizedStringForStatusCode:urlResponse.statusCode];
  150. resp_msg = err_msg;
  151. }
  152. [ret setValue:[NSString stringWithFormat:@"%d",RESULT_NET_ERROR] forKey:@"result"];
  153. [ret setValue:err_msg forKey:@"err_msg"];
  154. [ret setValue:resp_msg forKey:@"resp_msg"];
  155. [ret setValue:[NSString stringWithFormat:@"%ld",(long)urlResponse.statusCode] forKey:@"resp_code"];
  156. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ret
  157. options:0
  158. error:nil];
  159. if(![url isEqualToString:recorder_url])
  160. {
  161. [self err_log:[RAUtils base64en:[RAConvertor dict2string:params]] result:[RAUtils base64en:[RAConvertor dict2string:ret]] module:url code:RESULT_NET_ERROR];
  162. }
  163. return jsonData;
  164. }
  165. else
  166. {
  167. // NSString* err_msg = [error localizedDescription];
  168. NSMutableString *str = [[NSMutableString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
  169. DebugLog(@"data string: %@",str);
  170. NSError *error1 = nil;
  171. NSMutableDictionary* jsobj = [[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error1] mutableCopy];
  172. if(jsobj==nil)// 服务器返回不是json
  173. {
  174. jsobj=[[NSMutableDictionary alloc] init];
  175. [jsobj setValue:[NSNumber numberWithInt:RESULT_NO_RESPONSE] forKey:@"result"];
  176. }
  177. if([jsobj[@"encrypt"] boolValue]==true)
  178. {
  179. jsobj = decryptBlock(jsobj);
  180. }
  181. if (resultBlock) {
  182. jsobj = resultBlock(jsobj);
  183. }
  184. int result=[[jsobj valueForKey:@"result"] intValue];
  185. if(![url isEqualToString:recorder_url]&&/*![url isEqualToString:URL_DOWNLOAD_OFFLINE]&&*/result!=2&&result!=99)
  186. {
  187. [self err_log:[RAUtils base64en:[RAConvertor dict2string:params]] result:[RAUtils base64en:str] module:url code:result];
  188. }
  189. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsobj
  190. options:0
  191. error:nil];
  192. return jsonData;
  193. }
  194. return responseData;
  195. }
  196. }
  197. +(NSDictionary*)err_log:(NSString*) up_params result:(NSString*)result module:(NSString*) module code:(int) code//device:(NSString*) device
  198. {
  199. // NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
  200. // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  201. // if(appDelegate.user!=nil)
  202. // [params setValue:appDelegate.user forKey:@"user"];
  203. //
  204. // [params setValue:up_params forKey:@"upparam"];
  205. //
  206. // [params setValue:[NSNumber numberWithInt:code ] forKey:@"code"];
  207. //
  208. // [params setValue:result forKey:@"result"];
  209. // [params setValue:module forKey:@"interfac"];
  210. //
  211. // [params setValue:[RAUtils base64en:[RAUtils dict2string: [RAUtils device_info]]] forKey:@"device"];
  212. //
  213. //
  214. // // [params setValue:module forKey:@"module"];
  215. //
  216. // // [[UIDevice currentDevice] name];
  217. //
  218. // // if(appDelegate.offline_mode)
  219. // // {
  220. // // return [OLDataProvider offline_notimpl];
  221. // // }
  222. // if(![self IsNetworkAvailable])
  223. // return [RAUtils error_json:RESULT_NET_NOTAVAILABLE err_msg:nil];
  224. //
  225. // NSData* json=[self get_json:URL_ERR_LOG parameters:params];
  226. // if(json==nil)
  227. // return nil;
  228. // NSError *error=nil;
  229. // NSDictionary *jsobj = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableLeaves error:&error];
  230. // return jsobj;
  231. // 子类没有处理err_log函数时的默认处理。
  232. NSMutableDictionary* jsobj = [@{@"result":@"2"} mutableCopy];
  233. return jsobj;
  234. }
  235. + (NSURLSessionTask *)upload:(NSData *)filedata FileName:(NSString*) filename Params:(NSDictionary *)params ToHost:(NSString *)urlString Result:(resultHandler)r Progress:(progressHandler)p DecryptHandler:(id (^)(NSString *))decrypt {
  236. // NSString *fileName = [filePath lastPathComponent];
  237. NSMutableData *dataM = [NSMutableData data];
  238. NSMutableString *stringM = [NSMutableString string];
  239. DebugLog(@"================parms==================");
  240. for (NSString *key in params) {
  241. [stringM appendString:[NSString stringWithFormat:@"--%@\r\n",BOUNDARY]];
  242. [stringM appendFormat:@"Content-Type: text/plain; charset=UTF-8\r\n"];
  243. [stringM appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
  244. [stringM appendFormat:@"%@\r\n",[params objectForKey:key]];
  245. DebugLog(@"parameter: key=%@ value=%@",key,[params objectForKey:key]);
  246. }
  247. DebugLog(@"================parms==================");
  248. // Apex Drivers 2018.5.5
  249. if (filedata) {
  250. [stringM appendString:[NSString stringWithFormat:@"--%@\r\n",BOUNDARY]];
  251. [stringM appendFormat:@"Content-Disposition: form-data; name=\"upfile\"; filename=%@\r\n",filename];
  252. [stringM appendString:@"Content-Type: application/mac-binary\r\n"];
  253. [stringM appendString:@"\r\n"];
  254. NSData *stringM_data = [stringM dataUsingEncoding:NSUTF8StringEncoding];
  255. [dataM appendData:stringM_data];
  256. // NSData *file_data = [NSData dataWithContentsOfFile:filePath];
  257. [dataM appendData:filedata];
  258. NSString *end = [NSString stringWithFormat:@"\r\n--%@--",BOUNDARY];
  259. [dataM appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
  260. } else {
  261. NSData *stringM_data = [stringM dataUsingEncoding:NSUTF8StringEncoding];
  262. [dataM appendData:stringM_data];
  263. NSString *end = [NSString stringWithFormat:@"\r\n--%@--",BOUNDARY];
  264. [dataM appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
  265. }
  266. // Data
  267. NSData *data = dataM;
  268. // 可变请求
  269. NSURL *url = [NSURL URLWithString:urlString];
  270. NSMutableURLRequest *requestM = [NSMutableURLRequest requestWithURL:url
  271. cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:JSON_TIMEOUT];
  272. // line note
  273. requestM.HTTPMethod = @"POST";
  274. // request header
  275. [requestM addValue:@"close" forHTTPHeaderField:@"Connection"];
  276. [requestM addValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",BOUNDARY] forHTTPHeaderField:@"Content-Type"];
  277. [requestM addValue:@"multipart/form-data" forHTTPHeaderField:@"enctype"];
  278. [requestM addValue:[NSString stringWithFormat:@"%lu", (unsigned long)[data length]] forHTTPHeaderField:@"Content-Length"];
  279. // request body
  280. requestM.HTTPBody = data;
  281. NSURLSession *urlSession = [self standSession];
  282. if (urlSession.delegate) {
  283. if ([urlSession.delegate isKindOfClass:[RANetworkTaskDelegate class]]) {
  284. RANetworkTaskDelegate *delegate = (RANetworkTaskDelegate *)urlSession.delegate;
  285. if (p) {
  286. delegate.p = p;
  287. }
  288. if (r) {
  289. delegate.r = r;
  290. }
  291. if (decrypt) {
  292. delegate.decryptHandler = decrypt;
  293. }
  294. }
  295. }
  296. NSURLSessionDataTask *dataTask = [urlSession uploadTaskWithRequest:requestM fromData:data];
  297. [dataTask resume];
  298. return dataTask;
  299. }
  300. + (NSURLSessionTask *)upload:(NSString *)filePath Params:(NSDictionary *)params ToHost:(NSString *)urlString Result:(resultHandler)r Progress:(progressHandler)p DecryptHandler:(id (^)(NSString *))decrypt {
  301. NSString *fileName = [filePath lastPathComponent];
  302. NSData *file_data = [NSData dataWithContentsOfFile:filePath];
  303. return [self upload:file_data FileName:fileName Params:params ToHost:urlString Result:r Progress:p DecryptHandler:decrypt];
  304. //
  305. // NSMutableData *dataM = [NSMutableData data];
  306. //
  307. // NSMutableString *stringM = [NSMutableString string];
  308. //
  309. //
  310. // DebugLog(@"================parms==================");
  311. //
  312. //
  313. //
  314. // for (NSString *key in params) {
  315. //
  316. // [stringM appendString:[NSString stringWithFormat:@"--%@\r\n",BOUNDARY]];
  317. // [stringM appendFormat:@"Content-Type: text/plain; charset=UTF-8\r\n"];
  318. // [stringM appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
  319. // [stringM appendFormat:@"%@\r\n",[params objectForKey:key]];
  320. //
  321. //
  322. // DebugLog(@"parameter: key=%@ value=%@",key,[params objectForKey:key]);
  323. // }
  324. // DebugLog(@"================parms==================");
  325. // [stringM appendString:[NSString stringWithFormat:@"--%@\r\n",BOUNDARY]];
  326. //
  327. // [stringM appendFormat:@"Content-Disposition: form-data; name=\"upfile\"; filename=%@\r\n",fileName];
  328. // [stringM appendString:@"Content-Type: application/mac-binary\r\n"];
  329. // [stringM appendString:@"\r\n"];
  330. //
  331. // NSData *stringM_data = [stringM dataUsingEncoding:NSUTF8StringEncoding];
  332. // [dataM appendData:stringM_data];
  333. //
  334. // NSData *file_data = [NSData dataWithContentsOfFile:filePath];
  335. // [dataM appendData:file_data];
  336. //
  337. // NSString *end = [NSString stringWithFormat:@"\r\n--%@--",BOUNDARY];
  338. // [dataM appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
  339. //
  340. // // Data
  341. // NSData *data = dataM;
  342. //
  343. //
  344. // // 可变请求
  345. // NSURL *url = [NSURL URLWithString:urlString];
  346. // NSMutableURLRequest *requestM = [NSMutableURLRequest requestWithURL:url
  347. // cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:JSON_TIMEOUT];
  348. // // line note
  349. // requestM.HTTPMethod = @"POST";
  350. //
  351. // // request header
  352. // [requestM addValue:@"close" forHTTPHeaderField:@"Connection"];
  353. //
  354. // [requestM addValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",BOUNDARY] forHTTPHeaderField:@"Content-Type"];
  355. //
  356. // [requestM addValue:[NSString stringWithFormat:@"%lu", (unsigned long)[data length]] forHTTPHeaderField:@"Content-Length"];
  357. //
  358. // // request body
  359. // requestM.HTTPBody = data;
  360. //
  361. //
  362. //
  363. // NSURLSession *urlSession = [self standSession];
  364. //
  365. // if (urlSession.delegate) {
  366. // if ([urlSession.delegate isKindOfClass:[RANetworkTaskDelegate class]]) {
  367. //
  368. // RANetworkTaskDelegate *delegate = (RANetworkTaskDelegate *)urlSession.delegate;
  369. //
  370. // if (p) {
  371. // delegate.p = p;
  372. // }
  373. //
  374. // if (r) {
  375. // delegate.r = r;
  376. // }
  377. //
  378. // if (decrypt) {
  379. // delegate.decryptHandler = decrypt;
  380. // }
  381. //
  382. // }
  383. // }
  384. //
  385. // NSURLSessionDataTask *dataTask = [urlSession uploadTaskWithRequest:requestM fromData:data];
  386. //
  387. // [dataTask resume];
  388. //
  389. // return dataTask;
  390. }
  391. + (NSURLSession *)standSession {
  392. NSURLSession *session = nil;
  393. RANetworkTaskDelegate *delegate = [RANetworkTaskDelegate sharedInstance];
  394. NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
  395. config.timeoutIntervalForRequest = JSON_TIMEOUT;
  396. NSOperationQueue *queue = [[NSOperationQueue alloc] init];
  397. session = [NSURLSession sessionWithConfiguration:config delegate:delegate delegateQueue:queue];
  398. return session;
  399. }
  400. + (NSURLSessionDownloadTask *)downloadFileOffset:(NSUInteger)offset Param:(NSDictionary *)param from:(NSString *)url method:(NSString *)method toPath:(NSString *)path progressHandler:(progressHandler)progressHandler completionHandler:(resultHandler)result {
  401. NSURLSession *sessoin = [self standSession];
  402. RANetworkTaskDelegate *delegate = (RANetworkTaskDelegate *)sessoin.delegate;
  403. delegate.downloadTask = YES;
  404. delegate.fileCachePath = path;
  405. if (progressHandler) {
  406. delegate.p = progressHandler;
  407. }
  408. if (result) {
  409. delegate.r = result;
  410. }
  411. NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
  412. req.HTTPMethod = method;
  413. if (offset > 0) {
  414. [req addValue:[NSString stringWithFormat:@"bytes=%ld-",(unsigned long)offset] forHTTPHeaderField:@"Range"];
  415. }
  416. // 拼接参数
  417. if (param && param.allValues.count > 0) {
  418. __block NSMutableArray *paramArr = [NSMutableArray array];
  419. [param enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
  420. [paramArr addObject:[NSString stringWithFormat:@"%@=%@",key,obj]];
  421. }];
  422. NSString *paramStr = [paramArr componentsJoinedByString:@"&"];
  423. req.HTTPBody = [paramStr dataUsingEncoding:NSUTF8StringEncoding];
  424. }
  425. NSURLSessionDownloadTask *downloadTask = [sessoin downloadTaskWithRequest:req];
  426. [downloadTask resume];
  427. return downloadTask;
  428. }
  429. #pragma mark new interface
  430. +(NSMutableDictionary*) prepare_addtional_params:(NSMutableDictionary* ) params
  431. {
  432. //
  433. // NSString *userAction = [params valueForKey:kAction];
  434. // NSMutableDictionary *extra = [[params valueForKey:kExtra] mutableCopy];
  435. // if ([userAction isEqualToString:@"Login"]) {
  436. // if (!extra) {
  437. // extra = [NSMutableDictionary dictionary];
  438. // }
  439. // [extra setObject:[params objectForKey:@"user"] forKey:@"user"];
  440. // }
  441. return params;
  442. }
  443. +(NSData*)request_interface_d : (NSString*) url parameters:(NSMutableDictionary *) params err_record_url:(NSString* )recorder_url completionHandler:(resultHandler)result retry:(int) retry
  444. {
  445. // __block int retry = 0;
  446. if(![NetworkUtils IsNetworkAvailable])
  447. {
  448. dispatch_async(dispatch_get_main_queue(), ^{
  449. if(result)
  450. result([[RAConvertor string2dict:[NSString stringWithFormat:@"{\"result\":%d}",RESULT_NET_NOTAVAILABLE]] mutableCopy]);
  451. });
  452. // return detailContent;
  453. return nil;
  454. }
  455. params = [self prepare_addtional_params:params];
  456. //repeat:
  457. // {
  458. // return [self fake_json:url];
  459. // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  460. //分界线的标识符
  461. NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
  462. //根据url初始化request
  463. NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
  464. cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
  465. timeoutInterval:JSON_TIMEOUT];
  466. //分界线 --AaB03x
  467. NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
  468. //结束符 AaB03x--
  469. NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
  470. //要上传的图片
  471. // UIImage *image=[params objectForKey:@"pic"];
  472. //得到图片的data
  473. /*
  474. // NSData* data = [NSData dataWithContentsOfFile:file_path];
  475. */
  476. //http body的字符串
  477. NSMutableString *body=[[NSMutableString alloc]init];
  478. // NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
  479. // [params setValue:@"handset_login" forKey:@"action"];
  480. // [headers setValue:[NSString stringWithFormat:@"%d",dataLength] forKey:@"Content-Length"];
  481. // [params setValue:appDelegate.sessionid forKey:@"sessionid"];
  482. // [params setValue:password forKey:@"password"];
  483. // [params setValue:[NSString stringWithFormat:@"%d",ver] forKey:@"auth_ver"];
  484. // [headers setValue:headQuerlString forKey:@"param"];
  485. //参数的集合的所有key的集合
  486. NSArray *keys= [params allKeys];
  487. DebugLog(@"================parms==================");
  488. //遍历keys
  489. for(int i=0;i<[keys count];i++)
  490. {
  491. //得到当前key
  492. NSString *key=[keys objectAtIndex:i];
  493. //如果key不是pic,说明value是字符类型,比如name:Boris
  494. if(![key isEqualToString:@"pic"])
  495. {
  496. //添加分界线,换行
  497. [body appendFormat:@"%@\r\n",MPboundary];
  498. //添加字段名称,换2行
  499. [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
  500. //添加字段的值
  501. [body appendFormat:@"%@\r\n",[params objectForKey:key]];
  502. DebugLog(@"parameter: key=%@ value=%@",key,[params objectForKey:key]);
  503. }
  504. }
  505. DebugLog(@"================parms==================");
  506. ////添加分界线,换行
  507. /* [body appendFormat:@"%@\r\n",MPboundary];
  508. //声明pic字段,文件名为boris.png
  509. NSString * file_format=[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"upfile\"; filename=\"%@\"\r\n", [file_path lastPathComponent]];
  510. [body appendFormat:@"%@", file_format];
  511. //声明上传文件的格式
  512. [body appendFormat:@"Content-Type: application/zip\r\n\r\n"];
  513. */
  514. //声明结束符:--AaB03x--
  515. NSString *end=[[NSString alloc]initWithFormat:@"%@",endMPboundary];
  516. //声明myRequestData,用来放入http body
  517. NSMutableData *myRequestData=[NSMutableData data];
  518. //将body字符串转化为UTF8格式的二进制
  519. [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
  520. /*
  521. //将image的data加入
  522. [myRequestData appendData:data];
  523. */
  524. //加入结束符--AaB03x--
  525. [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
  526. //设置HTTPHeader中Content-Type的值
  527. NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
  528. //设置HTTPHeader
  529. [request setValue:content forHTTPHeaderField:@"Content-Type"];
  530. [request setValue:@"multipart/form-data" forHTTPHeaderField:@"enctype"];
  531. // 关闭keep alive
  532. [request setValue:@"close" forHTTPHeaderField:@"Connection"];
  533. //设置Content-Length
  534. [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
  535. //设置http body
  536. [request setHTTPBody:myRequestData];
  537. //http method
  538. [request setHTTPMethod:@"POST"];
  539. NSLog([[NSString alloc] initWithData:myRequestData encoding:NSUTF8StringEncoding]);
  540. NSURLSession *urlSession = [self standSession];
  541. if (urlSession.delegate) {
  542. if ([urlSession.delegate isKindOfClass:[RANetworkTaskDelegate class]]) {
  543. RANetworkTaskDelegate *delegate = (RANetworkTaskDelegate *)urlSession.delegate;
  544. // if (p) {
  545. // delegate.p = p;
  546. // }
  547. //
  548. if (result) {
  549. delegate.r = result;
  550. }
  551. //
  552. // if (decrypt) {
  553. // delegate.decryptHandler = decrypt;
  554. // }
  555. }
  556. }
  557. NSURLSessionDataTask *dataTask = [urlSession dataTaskWithRequest:request];
  558. // [dataTask1 resume];
  559. // NSURLSessionDataTask *dataTask =[urlSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  560. //
  561. // NSData *responseData =data;
  562. // NSHTTPURLResponse* urlResponse =response;
  563. // if (responseData==nil) {
  564. //
  565. // // DebugLog(@"response error:%@", [error localizedDescription]);
  566. //
  567. //
  568. // NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
  569. // //#define RESULT_FALSE 0
  570. // //#define RESULT_TRUE 2
  571. // //#define RESULT_NET_ERROR -3
  572. // //#define RESULT_NET_NOTAVAILABLE -4
  573. // //#define RESULT_ERROR -5
  574. // //#define RESULT_LOCALFILE_ERROR -7
  575. // //#define RESULT_USERAUTH_ERROR -9
  576. // //#define RESULT_UPDATE_USERAUTH_ERROR -11
  577. // //#define RESULT_SESSION_EXPIRED -13
  578. // //#define RESULT_VER_LOW
  579. //
  580. // // NSString * moreinfo = error.description ;
  581. //
  582. // NSString* err_msg = [error localizedDescription];
  583. //
  584. //
  585. // //-----------------retry 3 times for error code -1005------------------------
  586. // if(error.code==-1005&&retry<3)
  587. // {
  588. // int new_retry=retry+1;
  589. // [self request_interface:url parameters:params err_record_url:recorder_url completionHandler:result retry:new_retry];
  590. // return;
  591. // // retry++;
  592. // // goto repeat;
  593. //
  594. // }
  595. // //-----------------end retry 3 times for error code -1005------------------------
  596. //
  597. // NSDictionary* error_json = [RAUtils error_dict:error];
  598. // [ret setObject:error_json forKey:@"err_obj"];
  599. // NSString* resp_msg= nil;
  600. //
  601. // if(err_msg.length==0)
  602. // {
  603. // err_msg =[NSHTTPURLResponse localizedStringForStatusCode:urlResponse.statusCode];
  604. // resp_msg = err_msg;
  605. // }
  606. // [ret setValue:[NSString stringWithFormat:@"%d",RESULT_NET_ERROR] forKey:@"result"];
  607. // [ret setValue:err_msg forKey:@"err_msg"];
  608. // [ret setValue:resp_msg forKey:@"resp_msg"];
  609. // [ret setValue:[NSString stringWithFormat:@"%ld",(long)urlResponse.statusCode] forKey:@"resp_code"];
  610. //
  611. //
  612. // NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ret
  613. // options:0
  614. // error:nil];
  615. // if(![url isEqualToString:recorder_url])
  616. // {
  617. // [self err_log:[RAUtils base64en:[RAConvertor dict2string:params]] result:[RAUtils base64en:[RAConvertor dict2string:ret]] module:url code:RESULT_NET_ERROR];
  618. // }
  619. // dispatch_async(dispatch_get_main_queue(), ^{
  620. // if(result)
  621. // return result([[RAConvertor data2dict:jsonData] mutableCopy]);
  622. // });
  623. // }
  624. // else
  625. // {
  626. // NSDictionary* dict =[RAConvertor data2dict:responseData];
  627. // dispatch_async(dispatch_get_main_queue(), ^{
  628. // if(result)
  629. // return result([[RAConvertor data2dict:responseData] mutableCopy]);
  630. // });
  631. //
  632. // }
  633. //
  634. // }];
  635. //// NSURLSessionDataTask *dataTask = [urlSession dataTaskWithRequest:request ];
  636. //
  637. [dataTask resume];
  638. return nil;
  639. //
  640. //
  641. // NSHTTPURLResponse* urlResponse = nil;
  642. //
  643. // NSError *error = nil;
  644. // NSLog(@"begin request %@",url);
  645. //
  646. // NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
  647. //
  648. //
  649. // DebugLog(@"url: %@",url);
  650. //
  651. // DebugLog(@"response: %@",[NSHTTPURLResponse localizedStringForStatusCode:urlResponse.statusCode]);
  652. //
  653. //
  654. // NSLog(@"get response");
  655. // if (responseData==nil) {
  656. //
  657. // // DebugLog(@"response error:%@", [error localizedDescription]);
  658. //
  659. //
  660. // NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
  661. // //#define RESULT_FALSE 0
  662. // //#define RESULT_TRUE 2
  663. // //#define RESULT_NET_ERROR -3
  664. // //#define RESULT_NET_NOTAVAILABLE -4
  665. // //#define RESULT_ERROR -5
  666. // //#define RESULT_LOCALFILE_ERROR -7
  667. // //#define RESULT_USERAUTH_ERROR -9
  668. // //#define RESULT_UPDATE_USERAUTH_ERROR -11
  669. // //#define RESULT_SESSION_EXPIRED -13
  670. // //#define RESULT_VER_LOW
  671. //
  672. // // NSString * moreinfo = error.description ;
  673. //
  674. // NSString* err_msg = [error localizedDescription];
  675. //
  676. //
  677. // //-----------------retry 3 times for error code -1005------------------------
  678. // if(error.code==-1005&&retry<3)
  679. // {
  680. // retry++;
  681. // goto repeat;
  682. //
  683. // }
  684. // //-----------------end retry 3 times for error code -1005------------------------
  685. //
  686. // NSDictionary* error_json = [RAUtils error_dict:error];
  687. // [ret setObject:error_json forKey:@"err_obj"];
  688. // NSString* resp_msg= nil;
  689. //
  690. // if(err_msg.length==0)
  691. // {
  692. // err_msg =[NSHTTPURLResponse localizedStringForStatusCode:urlResponse.statusCode];
  693. // resp_msg = err_msg;
  694. // }
  695. // [ret setValue:[NSString stringWithFormat:@"%d",RESULT_NET_ERROR] forKey:@"result"];
  696. // [ret setValue:err_msg forKey:@"err_msg"];
  697. // [ret setValue:resp_msg forKey:@"resp_msg"];
  698. // [ret setValue:[NSString stringWithFormat:@"%ld",(long)urlResponse.statusCode] forKey:@"resp_code"];
  699. //
  700. //
  701. // NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ret
  702. // options:0
  703. // error:nil];
  704. // if(![url isEqualToString:recorder_url])
  705. // {
  706. // [self err_log:[RAUtils base64en:[RAConvertor dict2string:params]] result:[RAUtils base64en:[RAConvertor dict2string:ret]] module:url code:RESULT_NET_ERROR];
  707. // }
  708. // return jsonData;
  709. //
  710. // }
  711. // else
  712. // {
  713. // // NSString* err_msg = [error localizedDescription];
  714. // NSMutableString *str = [[NSMutableString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
  715. //
  716. // DebugLog(@"data string: %@",str);
  717. // NSError *error1 = nil;
  718. //
  719. // NSMutableDictionary* jsobj = [[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error1] mutableCopy];
  720. //
  721. // if(jsobj==nil)// 服务器返回不是json
  722. // {
  723. //
  724. // jsobj=[[NSMutableDictionary alloc] init];
  725. // [jsobj setValue:[NSNumber numberWithInt:RESULT_NO_RESPONSE] forKey:@"result"];
  726. //
  727. // }
  728. //// if([jsobj[@"encrypt"] boolValue]==true)
  729. //// {
  730. //// jsobj = decryptBlock(jsobj);
  731. //// }
  732. //// if (resultBlock) {
  733. //// jsobj = resultBlock(jsobj);
  734. //// }
  735. //
  736. // int result=[[jsobj valueForKey:@"result"] intValue];
  737. // if(![url isEqualToString:recorder_url]&&/*![url isEqualToString:URL_DOWNLOAD_OFFLINE]&&*/result!=2&&result!=99)
  738. // {
  739. // [self err_log:[RAUtils base64en:[RAConvertor dict2string:params]] result:[RAUtils base64en:str] module:url code:result];
  740. // }
  741. // NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsobj
  742. // options:0
  743. // error:nil];
  744. // return jsonData;
  745. //
  746. // }
  747. // return responseData;
  748. // }
  749. }
  750. +(void)request_interface : (NSString*) url parameters:(NSMutableDictionary *) params err_record_url:(NSString* )recorder_url completionHandler:(resultHandler)result retry:(int) retry
  751. {
  752. // __block int retry = 0;
  753. if(![NetworkUtils IsNetworkAvailable])
  754. {
  755. dispatch_async(dispatch_get_main_queue(), ^{
  756. if(result)
  757. result([[RAConvertor string2dict:[NSString stringWithFormat:@"{\"result\":%d}",RESULT_NET_NOTAVAILABLE]] mutableCopy]);
  758. });
  759. // return detailContent;
  760. return ;
  761. }
  762. params = [self prepare_addtional_params:params];
  763. //repeat:
  764. // {
  765. // return [self fake_json:url];
  766. // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  767. //分界线的标识符
  768. NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
  769. //根据url初始化request
  770. NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
  771. cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
  772. timeoutInterval:JSON_TIMEOUT];
  773. //分界线 --AaB03x
  774. NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
  775. //结束符 AaB03x--
  776. NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
  777. //要上传的图片
  778. // UIImage *image=[params objectForKey:@"pic"];
  779. //得到图片的data
  780. /*
  781. // NSData* data = [NSData dataWithContentsOfFile:file_path];
  782. */
  783. //http body的字符串
  784. NSMutableString *body=[[NSMutableString alloc]init];
  785. // NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
  786. // [params setValue:@"handset_login" forKey:@"action"];
  787. // [headers setValue:[NSString stringWithFormat:@"%d",dataLength] forKey:@"Content-Length"];
  788. // [params setValue:appDelegate.sessionid forKey:@"sessionid"];
  789. // [params setValue:password forKey:@"password"];
  790. // [params setValue:[NSString stringWithFormat:@"%d",ver] forKey:@"auth_ver"];
  791. // [headers setValue:headQuerlString forKey:@"param"];
  792. //参数的集合的所有key的集合
  793. NSArray *keys= [params allKeys];
  794. DebugLog(@"================parms==================");
  795. //遍历keys
  796. for(int i=0;i<[keys count];i++)
  797. {
  798. //得到当前key
  799. NSString *key=[keys objectAtIndex:i];
  800. //如果key不是pic,说明value是字符类型,比如name:Boris
  801. if(![key isEqualToString:@"pic"])
  802. {
  803. //添加分界线,换行
  804. [body appendFormat:@"%@\r\n",MPboundary];
  805. //添加字段名称,换2行
  806. [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
  807. //添加字段的值
  808. [body appendFormat:@"%@\r\n",[params objectForKey:key]];
  809. DebugLog(@"parameter: key=%@ value=%@",key,[params objectForKey:key]);
  810. }
  811. }
  812. DebugLog(@"================parms==================");
  813. ////添加分界线,换行
  814. /* [body appendFormat:@"%@\r\n",MPboundary];
  815. //声明pic字段,文件名为boris.png
  816. NSString * file_format=[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"upfile\"; filename=\"%@\"\r\n", [file_path lastPathComponent]];
  817. [body appendFormat:@"%@", file_format];
  818. //声明上传文件的格式
  819. [body appendFormat:@"Content-Type: application/zip\r\n\r\n"];
  820. */
  821. //声明结束符:--AaB03x--
  822. NSString *end=[[NSString alloc]initWithFormat:@"%@",endMPboundary];
  823. //声明myRequestData,用来放入http body
  824. NSMutableData *myRequestData=[NSMutableData data];
  825. //将body字符串转化为UTF8格式的二进制
  826. [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
  827. /*
  828. //将image的data加入
  829. [myRequestData appendData:data];
  830. */
  831. //加入结束符--AaB03x--
  832. [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
  833. //设置HTTPHeader中Content-Type的值
  834. NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
  835. //设置HTTPHeader
  836. [request setValue:content forHTTPHeaderField:@"Content-Type"];
  837. [request setValue:@"multipart/form-data" forHTTPHeaderField:@"enctype"];
  838. // 关闭keep alive
  839. [request setValue:@"close" forHTTPHeaderField:@"Connection"];
  840. //设置Content-Length
  841. [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
  842. //设置http body
  843. [request setHTTPBody:myRequestData];
  844. //http method
  845. [request setHTTPMethod:@"POST"];
  846. NSURLSession *urlSession = [self standSession];
  847. if (urlSession.delegate) {
  848. if ([urlSession.delegate isKindOfClass:[RANetworkTaskDelegate class]]) {
  849. RANetworkTaskDelegate *delegate = (RANetworkTaskDelegate *)urlSession.delegate;
  850. // if (p) {
  851. // delegate.p = p;
  852. // }
  853. //
  854. if (result) {
  855. delegate.r = result;
  856. }
  857. //
  858. // if (decrypt) {
  859. // delegate.decryptHandler = decrypt;
  860. // }
  861. }
  862. }
  863. NSURLSessionDataTask *dataTask =[urlSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  864. NSData *responseData =data;
  865. NSHTTPURLResponse* urlResponse =response;
  866. if (responseData==nil) {
  867. // DebugLog(@"response error:%@", [error localizedDescription]);
  868. NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
  869. //#define RESULT_FALSE 0
  870. //#define RESULT_TRUE 2
  871. //#define RESULT_NET_ERROR -3
  872. //#define RESULT_NET_NOTAVAILABLE -4
  873. //#define RESULT_ERROR -5
  874. //#define RESULT_LOCALFILE_ERROR -7
  875. //#define RESULT_USERAUTH_ERROR -9
  876. //#define RESULT_UPDATE_USERAUTH_ERROR -11
  877. //#define RESULT_SESSION_EXPIRED -13
  878. //#define RESULT_VER_LOW
  879. // NSString * moreinfo = error.description ;
  880. NSString* err_msg = [error localizedDescription];
  881. //-----------------retry 3 times for error code -1005------------------------
  882. if(error.code==-1005&&retry<3)
  883. {
  884. int new_retry=retry+1;
  885. [self request_interface:url parameters:params err_record_url:recorder_url completionHandler:result retry:new_retry];
  886. return;
  887. // retry++;
  888. // goto repeat;
  889. }
  890. //-----------------end retry 3 times for error code -1005------------------------
  891. NSDictionary* error_json = [RAUtils error_dict:error];
  892. [ret setObject:error_json forKey:@"err_obj"];
  893. NSString* resp_msg= nil;
  894. if(err_msg.length==0)
  895. {
  896. err_msg =[NSHTTPURLResponse localizedStringForStatusCode:urlResponse.statusCode];
  897. resp_msg = err_msg;
  898. }
  899. [ret setValue:[NSString stringWithFormat:@"%d",RESULT_NET_ERROR] forKey:@"result"];
  900. [ret setValue:err_msg forKey:@"err_msg"];
  901. [ret setValue:resp_msg forKey:@"resp_msg"];
  902. [ret setValue:[NSString stringWithFormat:@"%ld",(long)urlResponse.statusCode] forKey:@"resp_code"];
  903. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ret
  904. options:0
  905. error:nil];
  906. if(![url isEqualToString:recorder_url])
  907. {
  908. [self err_log:[RAUtils base64en:[RAConvertor dict2string:params]] result:[RAUtils base64en:[RAConvertor dict2string:ret]] module:url code:RESULT_NET_ERROR];
  909. }
  910. dispatch_async(dispatch_get_main_queue(), ^{
  911. if(result)
  912. return result([[RAConvertor data2dict:jsonData] mutableCopy]);
  913. });
  914. }
  915. else
  916. {
  917. NSDictionary* dict =[RAConvertor data2dict:responseData];
  918. dispatch_async(dispatch_get_main_queue(), ^{
  919. if(result)
  920. return result([[RAConvertor data2dict:responseData] mutableCopy]);
  921. });
  922. }
  923. }];
  924. // NSURLSessionDataTask *dataTask = [urlSession dataTaskWithRequest:request ];
  925. [dataTask resume];
  926. return ;
  927. //
  928. //
  929. // NSHTTPURLResponse* urlResponse = nil;
  930. //
  931. // NSError *error = nil;
  932. // NSLog(@"begin request %@",url);
  933. //
  934. // NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
  935. //
  936. //
  937. // DebugLog(@"url: %@",url);
  938. //
  939. // DebugLog(@"response: %@",[NSHTTPURLResponse localizedStringForStatusCode:urlResponse.statusCode]);
  940. //
  941. //
  942. // NSLog(@"get response");
  943. // if (responseData==nil) {
  944. //
  945. // // DebugLog(@"response error:%@", [error localizedDescription]);
  946. //
  947. //
  948. // NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
  949. // //#define RESULT_FALSE 0
  950. // //#define RESULT_TRUE 2
  951. // //#define RESULT_NET_ERROR -3
  952. // //#define RESULT_NET_NOTAVAILABLE -4
  953. // //#define RESULT_ERROR -5
  954. // //#define RESULT_LOCALFILE_ERROR -7
  955. // //#define RESULT_USERAUTH_ERROR -9
  956. // //#define RESULT_UPDATE_USERAUTH_ERROR -11
  957. // //#define RESULT_SESSION_EXPIRED -13
  958. // //#define RESULT_VER_LOW
  959. //
  960. // // NSString * moreinfo = error.description ;
  961. //
  962. // NSString* err_msg = [error localizedDescription];
  963. //
  964. //
  965. // //-----------------retry 3 times for error code -1005------------------------
  966. // if(error.code==-1005&&retry<3)
  967. // {
  968. // retry++;
  969. // goto repeat;
  970. //
  971. // }
  972. // //-----------------end retry 3 times for error code -1005------------------------
  973. //
  974. // NSDictionary* error_json = [RAUtils error_dict:error];
  975. // [ret setObject:error_json forKey:@"err_obj"];
  976. // NSString* resp_msg= nil;
  977. //
  978. // if(err_msg.length==0)
  979. // {
  980. // err_msg =[NSHTTPURLResponse localizedStringForStatusCode:urlResponse.statusCode];
  981. // resp_msg = err_msg;
  982. // }
  983. // [ret setValue:[NSString stringWithFormat:@"%d",RESULT_NET_ERROR] forKey:@"result"];
  984. // [ret setValue:err_msg forKey:@"err_msg"];
  985. // [ret setValue:resp_msg forKey:@"resp_msg"];
  986. // [ret setValue:[NSString stringWithFormat:@"%ld",(long)urlResponse.statusCode] forKey:@"resp_code"];
  987. //
  988. //
  989. // NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ret
  990. // options:0
  991. // error:nil];
  992. // if(![url isEqualToString:recorder_url])
  993. // {
  994. // [self err_log:[RAUtils base64en:[RAConvertor dict2string:params]] result:[RAUtils base64en:[RAConvertor dict2string:ret]] module:url code:RESULT_NET_ERROR];
  995. // }
  996. // return jsonData;
  997. //
  998. // }
  999. // else
  1000. // {
  1001. // // NSString* err_msg = [error localizedDescription];
  1002. // NSMutableString *str = [[NSMutableString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
  1003. //
  1004. // DebugLog(@"data string: %@",str);
  1005. // NSError *error1 = nil;
  1006. //
  1007. // NSMutableDictionary* jsobj = [[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error1] mutableCopy];
  1008. //
  1009. // if(jsobj==nil)// 服务器返回不是json
  1010. // {
  1011. //
  1012. // jsobj=[[NSMutableDictionary alloc] init];
  1013. // [jsobj setValue:[NSNumber numberWithInt:RESULT_NO_RESPONSE] forKey:@"result"];
  1014. //
  1015. // }
  1016. //// if([jsobj[@"encrypt"] boolValue]==true)
  1017. //// {
  1018. //// jsobj = decryptBlock(jsobj);
  1019. //// }
  1020. //// if (resultBlock) {
  1021. //// jsobj = resultBlock(jsobj);
  1022. //// }
  1023. //
  1024. // int result=[[jsobj valueForKey:@"result"] intValue];
  1025. // if(![url isEqualToString:recorder_url]&&/*![url isEqualToString:URL_DOWNLOAD_OFFLINE]&&*/result!=2&&result!=99)
  1026. // {
  1027. // [self err_log:[RAUtils base64en:[RAConvertor dict2string:params]] result:[RAUtils base64en:str] module:url code:result];
  1028. // }
  1029. // NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsobj
  1030. // options:0
  1031. // error:nil];
  1032. // return jsonData;
  1033. //
  1034. // }
  1035. // return responseData;
  1036. // }
  1037. }
  1038. +(void)request_file_1 : (NSString*) url parameters:(NSMutableDictionary *) params err_record_url:(NSString* )recorder_url completionHandler:(resultHandler)result
  1039. /* dataHandler:(dataHandler)returndata*/
  1040. {
  1041. // __block int retry = 0;
  1042. if(![NetworkUtils IsNetworkAvailable])
  1043. {
  1044. dispatch_async(dispatch_get_main_queue(), ^{
  1045. if(result)
  1046. result([[RAConvertor string2dict:[NSString stringWithFormat:@"{'result':%d}",RESULT_NET_NOTAVAILABLE]] mutableCopy]);
  1047. });
  1048. // return detailContent;
  1049. return ;
  1050. }
  1051. params = [self prepare_addtional_params:params];
  1052. //repeat:
  1053. // {
  1054. // return [self fake_json:url];
  1055. // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  1056. //分界线的标识符
  1057. NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
  1058. //根据url初始化request
  1059. NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
  1060. cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
  1061. timeoutInterval:JSON_TIMEOUT];
  1062. //分界线 --AaB03x
  1063. NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
  1064. //结束符 AaB03x--
  1065. NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
  1066. //要上传的图片
  1067. // UIImage *image=[params objectForKey:@"pic"];
  1068. //得到图片的data
  1069. /*
  1070. // NSData* data = [NSData dataWithContentsOfFile:file_path];
  1071. */
  1072. //http body的字符串
  1073. NSMutableString *body=[[NSMutableString alloc]init];
  1074. // NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
  1075. // [params setValue:@"handset_login" forKey:@"action"];
  1076. // [headers setValue:[NSString stringWithFormat:@"%d",dataLength] forKey:@"Content-Length"];
  1077. // [params setValue:appDelegate.sessionid forKey:@"sessionid"];
  1078. // [params setValue:password forKey:@"password"];
  1079. // [params setValue:[NSString stringWithFormat:@"%d",ver] forKey:@"auth_ver"];
  1080. // [headers setValue:headQuerlString forKey:@"param"];
  1081. //参数的集合的所有key的集合
  1082. NSArray *keys= [params allKeys];
  1083. DebugLog(@"================parms==================");
  1084. //遍历keys
  1085. for(int i=0;i<[keys count];i++)
  1086. {
  1087. //得到当前key
  1088. NSString *key=[keys objectAtIndex:i];
  1089. //如果key不是pic,说明value是字符类型,比如name:Boris
  1090. if(![key isEqualToString:@"pic"])
  1091. {
  1092. //添加分界线,换行
  1093. [body appendFormat:@"%@\r\n",MPboundary];
  1094. //添加字段名称,换2行
  1095. [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
  1096. //添加字段的值
  1097. [body appendFormat:@"%@\r\n",[params objectForKey:key]];
  1098. DebugLog(@"parameter: key=%@ value=%@",key,[params objectForKey:key]);
  1099. }
  1100. }
  1101. DebugLog(@"================parms==================");
  1102. ////添加分界线,换行
  1103. /* [body appendFormat:@"%@\r\n",MPboundary];
  1104. //声明pic字段,文件名为boris.png
  1105. NSString * file_format=[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"upfile\"; filename=\"%@\"\r\n", [file_path lastPathComponent]];
  1106. [body appendFormat:@"%@", file_format];
  1107. //声明上传文件的格式
  1108. [body appendFormat:@"Content-Type: application/zip\r\n\r\n"];
  1109. */
  1110. //声明结束符:--AaB03x--
  1111. NSString *end=[[NSString alloc]initWithFormat:@"%@",endMPboundary];
  1112. //声明myRequestData,用来放入http body
  1113. NSMutableData *myRequestData=[NSMutableData data];
  1114. //将body字符串转化为UTF8格式的二进制
  1115. [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
  1116. /*
  1117. //将image的data加入
  1118. [myRequestData appendData:data];
  1119. */
  1120. //加入结束符--AaB03x--
  1121. [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
  1122. //设置HTTPHeader中Content-Type的值
  1123. NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
  1124. //设置HTTPHeader
  1125. [request setValue:content forHTTPHeaderField:@"Content-Type"];
  1126. [request setValue:@"multipart/form-data" forHTTPHeaderField:@"enctype"];
  1127. // 关闭keep alive
  1128. [request setValue:@"close" forHTTPHeaderField:@"Connection"];
  1129. //设置Content-Length
  1130. [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
  1131. //设置http body
  1132. [request setHTTPBody:myRequestData];
  1133. //http method
  1134. [request setHTTPMethod:@"POST"];
  1135. NSURLSession *urlSession = [self standSession];
  1136. if (urlSession.delegate) {
  1137. if ([urlSession.delegate isKindOfClass:[RANetworkTaskDelegate class]]) {
  1138. RANetworkTaskDelegate *delegate = (RANetworkTaskDelegate *)urlSession.delegate;
  1139. // if (p) {
  1140. // delegate.p = p;
  1141. // }
  1142. //
  1143. if (result) {
  1144. delegate.r = result;
  1145. }
  1146. //
  1147. // if (decrypt) {
  1148. // delegate.decryptHandler = decrypt;
  1149. // }
  1150. }
  1151. }
  1152. NSURLSessionDownloadTask* downloadTask=[urlSession downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  1153. NSHTTPURLResponse* urlResponse =response;
  1154. NSData* data =[NSData dataWithContentsOfURL:location] ;
  1155. NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
  1156. if(data==nil)
  1157. {
  1158. NSString* err_msg = [error localizedDescription];
  1159. NSDictionary* error_json = [RAUtils error_dict:error];
  1160. [ret setObject:error_json forKey:@"err_obj"];
  1161. NSString* resp_msg= nil;
  1162. if(err_msg.length==0)
  1163. {
  1164. err_msg =[NSHTTPURLResponse localizedStringForStatusCode:urlResponse.statusCode];
  1165. resp_msg = err_msg;
  1166. }
  1167. [ret setValue:[NSString stringWithFormat:@"%d",RESULT_NET_ERROR] forKey:@"result"];
  1168. [ret setValue:err_msg forKey:@"err_msg"];
  1169. [ret setValue:resp_msg forKey:@"resp_msg"];
  1170. [ret setValue:[NSString stringWithFormat:@"%ld",(long)urlResponse.statusCode] forKey:@"resp_code"];
  1171. dispatch_async(dispatch_get_main_queue(), ^{
  1172. if(result)
  1173. result(ret);
  1174. });
  1175. }
  1176. else
  1177. {
  1178. NSString *cacheDir = NSTemporaryDirectory();
  1179. if (![[NSFileManager defaultManager] fileExistsAtPath:cacheDir]) {
  1180. [[NSFileManager defaultManager] createDirectoryAtPath:cacheDir withIntermediateDirectories:NO attributes:nil error:nil];
  1181. }
  1182. ret[@"result"]=@"2";
  1183. ret[@"data"]=data;
  1184. ret[@"path"]=[location absoluteString];
  1185. dispatch_async(dispatch_get_main_queue(), ^{
  1186. if(result)
  1187. result(ret);
  1188. });
  1189. }
  1190. // if(returndata)
  1191. // {
  1192. // returndata(data);
  1193. // }
  1194. }];
  1195. [downloadTask resume];
  1196. return ;
  1197. //
  1198. // NSURLSessionDataTask *dataTask =[urlSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  1199. //
  1200. // NSData *responseData =data;
  1201. // NSHTTPURLResponse* urlResponse =response;
  1202. // if (responseData==nil) {
  1203. //
  1204. // // DebugLog(@"response error:%@", [error localizedDescription]);
  1205. //
  1206. //
  1207. // NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
  1208. // //#define RESULT_FALSE 0
  1209. // //#define RESULT_TRUE 2
  1210. // //#define RESULT_NET_ERROR -3
  1211. // //#define RESULT_NET_NOTAVAILABLE -4
  1212. // //#define RESULT_ERROR -5
  1213. // //#define RESULT_LOCALFILE_ERROR -7
  1214. // //#define RESULT_USERAUTH_ERROR -9
  1215. // //#define RESULT_UPDATE_USERAUTH_ERROR -11
  1216. // //#define RESULT_SESSION_EXPIRED -13
  1217. // //#define RESULT_VER_LOW
  1218. //
  1219. // // NSString * moreinfo = error.description ;
  1220. //
  1221. // NSString* err_msg = [error localizedDescription];
  1222. //
  1223. //
  1224. // //-----------------retry 3 times for error code -1005------------------------
  1225. // if(error.code==-1005&&retry<3)
  1226. // {
  1227. // int new_retry=retry+1;
  1228. // [self request_interface:url parameters:params err_record_url:recorder_url completionHandler:result retry:new_retry];
  1229. // return;
  1230. // // retry++;
  1231. // // goto repeat;
  1232. //
  1233. // }
  1234. // //-----------------end retry 3 times for error code -1005------------------------
  1235. //
  1236. // NSDictionary* error_json = [RAUtils error_dict:error];
  1237. // [ret setObject:error_json forKey:@"err_obj"];
  1238. // NSString* resp_msg= nil;
  1239. //
  1240. // if(err_msg.length==0)
  1241. // {
  1242. // err_msg =[NSHTTPURLResponse localizedStringForStatusCode:urlResponse.statusCode];
  1243. // resp_msg = err_msg;
  1244. // }
  1245. // [ret setValue:[NSString stringWithFormat:@"%d",RESULT_NET_ERROR] forKey:@"result"];
  1246. // [ret setValue:err_msg forKey:@"err_msg"];
  1247. // [ret setValue:resp_msg forKey:@"resp_msg"];
  1248. // [ret setValue:[NSString stringWithFormat:@"%ld",(long)urlResponse.statusCode] forKey:@"resp_code"];
  1249. //
  1250. //
  1251. // NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ret
  1252. // options:0
  1253. // error:nil];
  1254. // if(![url isEqualToString:recorder_url])
  1255. // {
  1256. // [self err_log:[RAUtils base64en:[RAConvertor dict2string:params]] result:[RAUtils base64en:[RAConvertor dict2string:ret]] module:url code:RESULT_NET_ERROR];
  1257. // }
  1258. //
  1259. // if(result)
  1260. // return result([[RAConvertor data2dict:jsonData] mutableCopy]);
  1261. //
  1262. // }
  1263. // else
  1264. // {
  1265. // NSDictionary* dict =[RAConvertor data2dict:responseData];
  1266. // dispatch_async(dispatch_get_main_queue(), ^{
  1267. // if(result)
  1268. // return result([[RAConvertor data2dict:responseData] mutableCopy]);
  1269. // });
  1270. //
  1271. // }
  1272. //
  1273. // }];
  1274. //// NSURLSessionDataTask *dataTask = [urlSession dataTaskWithRequest:request ];
  1275. //
  1276. // [dataTask resume];
  1277. //
  1278. // return nil;
  1279. //
  1280. //
  1281. // NSHTTPURLResponse* urlResponse = nil;
  1282. //
  1283. // NSError *error = nil;
  1284. // NSLog(@"begin request %@",url);
  1285. //
  1286. // NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
  1287. //
  1288. //
  1289. // DebugLog(@"url: %@",url);
  1290. //
  1291. // DebugLog(@"response: %@",[NSHTTPURLResponse localizedStringForStatusCode:urlResponse.statusCode]);
  1292. //
  1293. //
  1294. // NSLog(@"get response");
  1295. // if (responseData==nil) {
  1296. //
  1297. // // DebugLog(@"response error:%@", [error localizedDescription]);
  1298. //
  1299. //
  1300. // NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
  1301. // //#define RESULT_FALSE 0
  1302. // //#define RESULT_TRUE 2
  1303. // //#define RESULT_NET_ERROR -3
  1304. // //#define RESULT_NET_NOTAVAILABLE -4
  1305. // //#define RESULT_ERROR -5
  1306. // //#define RESULT_LOCALFILE_ERROR -7
  1307. // //#define RESULT_USERAUTH_ERROR -9
  1308. // //#define RESULT_UPDATE_USERAUTH_ERROR -11
  1309. // //#define RESULT_SESSION_EXPIRED -13
  1310. // //#define RESULT_VER_LOW
  1311. //
  1312. // // NSString * moreinfo = error.description ;
  1313. //
  1314. // NSString* err_msg = [error localizedDescription];
  1315. //
  1316. //
  1317. // //-----------------retry 3 times for error code -1005------------------------
  1318. // if(error.code==-1005&&retry<3)
  1319. // {
  1320. // retry++;
  1321. // goto repeat;
  1322. //
  1323. // }
  1324. // //-----------------end retry 3 times for error code -1005------------------------
  1325. //
  1326. // NSDictionary* error_json = [RAUtils error_dict:error];
  1327. // [ret setObject:error_json forKey:@"err_obj"];
  1328. // NSString* resp_msg= nil;
  1329. //
  1330. // if(err_msg.length==0)
  1331. // {
  1332. // err_msg =[NSHTTPURLResponse localizedStringForStatusCode:urlResponse.statusCode];
  1333. // resp_msg = err_msg;
  1334. // }
  1335. // [ret setValue:[NSString stringWithFormat:@"%d",RESULT_NET_ERROR] forKey:@"result"];
  1336. // [ret setValue:err_msg forKey:@"err_msg"];
  1337. // [ret setValue:resp_msg forKey:@"resp_msg"];
  1338. // [ret setValue:[NSString stringWithFormat:@"%ld",(long)urlResponse.statusCode] forKey:@"resp_code"];
  1339. //
  1340. //
  1341. // NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ret
  1342. // options:0
  1343. // error:nil];
  1344. // if(![url isEqualToString:recorder_url])
  1345. // {
  1346. // [self err_log:[RAUtils base64en:[RAConvertor dict2string:params]] result:[RAUtils base64en:[RAConvertor dict2string:ret]] module:url code:RESULT_NET_ERROR];
  1347. // }
  1348. // return jsonData;
  1349. //
  1350. // }
  1351. // else
  1352. // {
  1353. // // NSString* err_msg = [error localizedDescription];
  1354. // NSMutableString *str = [[NSMutableString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
  1355. //
  1356. // DebugLog(@"data string: %@",str);
  1357. // NSError *error1 = nil;
  1358. //
  1359. // NSMutableDictionary* jsobj = [[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error1] mutableCopy];
  1360. //
  1361. // if(jsobj==nil)// 服务器返回不是json
  1362. // {
  1363. //
  1364. // jsobj=[[NSMutableDictionary alloc] init];
  1365. // [jsobj setValue:[NSNumber numberWithInt:RESULT_NO_RESPONSE] forKey:@"result"];
  1366. //
  1367. // }
  1368. //// if([jsobj[@"encrypt"] boolValue]==true)
  1369. //// {
  1370. //// jsobj = decryptBlock(jsobj);
  1371. //// }
  1372. //// if (resultBlock) {
  1373. //// jsobj = resultBlock(jsobj);
  1374. //// }
  1375. //
  1376. // int result=[[jsobj valueForKey:@"result"] intValue];
  1377. // if(![url isEqualToString:recorder_url]&&/*![url isEqualToString:URL_DOWNLOAD_OFFLINE]&&*/result!=2&&result!=99)
  1378. // {
  1379. // [self err_log:[RAUtils base64en:[RAConvertor dict2string:params]] result:[RAUtils base64en:str] module:url code:result];
  1380. // }
  1381. // NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsobj
  1382. // options:0
  1383. // error:nil];
  1384. // return jsonData;
  1385. //
  1386. // }
  1387. // return responseData;
  1388. // }
  1389. }
  1390. +(void)request_file_fast : (NSString*) url parameters:(NSMutableDictionary *) params completionHandler:(resultHandler)result
  1391. // Param:(NSDictionary *)param from:(NSString *)url completionHandler:(resultHandler)result
  1392. /* dataHandler:(dataHandler)returndata*/
  1393. {
  1394. if(![NetworkUtils IsNetworkAvailable])
  1395. {
  1396. dispatch_async(dispatch_get_main_queue(), ^{
  1397. if(result)
  1398. result([[RAConvertor string2dict:[NSString stringWithFormat:@"{\"result\":%d}",RESULT_NET_NOTAVAILABLE]] mutableCopy]);
  1399. });
  1400. // return detailContent;
  1401. return ;
  1402. }
  1403. params = [self prepare_addtional_params:params];
  1404. NSURLSession *urlSession = [self standSession];
  1405. // RANetworkTaskDelegate *delegate = (RANetworkTaskDelegate *)urlSession.delegate;
  1406. // delegate.downloadTask = YES;
  1407. // delegate.fileCachePath = path;
  1408. // if (progressHandler) {
  1409. // delegate.p = progressHandler;
  1410. // }
  1411. //
  1412. // if (result) {
  1413. // delegate.r = result;
  1414. // }
  1415. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
  1416. request.HTTPMethod = @"Post";
  1417. //
  1418. // if (offset > 0) {
  1419. // [request addValue:[NSString stringWithFormat:@"bytes=%ld-",(unsigned long)offset] forHTTPHeaderField:@"Range"];
  1420. // }
  1421. // 拼接参数
  1422. if (params && params.allValues.count > 0) {
  1423. __block NSMutableArray *paramArr = [NSMutableArray array];
  1424. [params enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
  1425. [paramArr addObject:[NSString stringWithFormat:@"%@=%@",key,obj]];
  1426. }];
  1427. NSString *paramStr = [paramArr componentsJoinedByString:@"&"];
  1428. request.HTTPBody = [paramStr dataUsingEncoding:NSUTF8StringEncoding];
  1429. }
  1430. NSURLSessionDownloadTask* downloadTask=[urlSession downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  1431. NSHTTPURLResponse* urlResponse =response;
  1432. NSData* data =[NSData dataWithContentsOfURL:location] ;
  1433. NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
  1434. if(data==nil)
  1435. {
  1436. NSString* err_msg = [error localizedDescription];
  1437. NSDictionary* error_json = [RAUtils error_dict:error];
  1438. [ret setObject:error_json forKey:@"err_obj"];
  1439. NSString* resp_msg= nil;
  1440. if(err_msg.length==0)
  1441. {
  1442. err_msg =[NSHTTPURLResponse localizedStringForStatusCode:urlResponse.statusCode];
  1443. resp_msg = err_msg;
  1444. }
  1445. [ret setValue:[NSString stringWithFormat:@"%d",RESULT_NET_ERROR] forKey:@"result"];
  1446. [ret setValue:err_msg forKey:@"err_msg"];
  1447. [ret setValue:resp_msg forKey:@"resp_msg"];
  1448. [ret setValue:[NSString stringWithFormat:@"%ld",(long)urlResponse.statusCode] forKey:@"resp_code"];
  1449. dispatch_async(dispatch_get_main_queue(), ^{
  1450. if(result)
  1451. result(ret);
  1452. });
  1453. }
  1454. else
  1455. {
  1456. NSString* path=NSTemporaryDirectory();
  1457. if (response.suggestedFilename) {
  1458. path = [path stringByAppendingPathComponent:response.suggestedFilename];
  1459. } else {
  1460. path = [path stringByAppendingPathComponent:[NSUUID UUID].UUIDString];
  1461. }
  1462. NSError *error = nil;
  1463. [[NSFileManager defaultManager] copyItemAtPath:location.path toPath:path error:&error];
  1464. // [[NSFileManager defaultManager] copyItemAtURL:[NSURL URLWithString:location.path] toURL:[NSURL URLWithString:path] error:&error];
  1465. // NSFileManager
  1466. // NSString *cacheDir = NSTemporaryDirectory();
  1467. //
  1468. // if (![[NSFileManager defaultManager] fileExistsAtPath:cacheDir]) {
  1469. // [[NSFileManager defaultManager] createDirectoryAtPath:cacheDir withIntermediateDirectories:NO attributes:nil error:nil];
  1470. // }
  1471. ret[@"result"]=@"2";
  1472. ret[@"data"]=data;
  1473. ret[@"path"]=path;//[location absoluteString];
  1474. dispatch_async(dispatch_get_main_queue(), ^{
  1475. if(result)
  1476. result(ret);
  1477. });
  1478. }
  1479. // if(returndata)
  1480. // {
  1481. // returndata(data);
  1482. // }
  1483. }];
  1484. [downloadTask resume];
  1485. return ;
  1486. }
  1487. @end