NetworkUtils.m 72 KB

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