NetworkUtils.m 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330
  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. NSHTTPURLResponse* urlResponse = nil;
  114. NSError *error = nil;
  115. NSLog(@"begin request %@",url);
  116. NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
  117. DebugLog(@"url: %@",url);
  118. DebugLog(@"response: %@",[NSHTTPURLResponse localizedStringForStatusCode:urlResponse.statusCode]);
  119. NSLog(@"get response");
  120. if (responseData==nil) {
  121. // DebugLog(@"response error:%@", [error localizedDescription]);
  122. NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
  123. //#define RESULT_FALSE 0
  124. //#define RESULT_TRUE 2
  125. //#define RESULT_NET_ERROR -3
  126. //#define RESULT_NET_NOTAVAILABLE -4
  127. //#define RESULT_ERROR -5
  128. //#define RESULT_LOCALFILE_ERROR -7
  129. //#define RESULT_USERAUTH_ERROR -9
  130. //#define RESULT_UPDATE_USERAUTH_ERROR -11
  131. //#define RESULT_SESSION_EXPIRED -13
  132. //#define RESULT_VER_LOW
  133. // NSString * moreinfo = error.description ;
  134. NSString* err_msg = [error localizedDescription];
  135. //-----------------retry 3 times for error code -1005------------------------
  136. if(error.code==-1005&&retry<3)
  137. {
  138. retry++;
  139. goto repeat;
  140. }
  141. //-----------------end retry 3 times for error code -1005------------------------
  142. NSDictionary* error_json = [RAUtils error_dict:error];
  143. [ret setObject:error_json forKey:@"err_obj"];
  144. NSString* resp_msg= nil;
  145. if(err_msg.length==0)
  146. {
  147. err_msg =[NSHTTPURLResponse localizedStringForStatusCode:urlResponse.statusCode];
  148. resp_msg = err_msg;
  149. }
  150. [ret setValue:[NSString stringWithFormat:@"%d",RESULT_NET_ERROR] forKey:@"result"];
  151. [ret setValue:err_msg forKey:@"err_msg"];
  152. [ret setValue:resp_msg forKey:@"resp_msg"];
  153. [ret setValue:[NSString stringWithFormat:@"%ld",(long)urlResponse.statusCode] forKey:@"resp_code"];
  154. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ret
  155. options:0
  156. error:nil];
  157. if(![url isEqualToString:recorder_url])
  158. {
  159. [self err_log:[RAUtils base64en:[RAConvertor dict2string:params]] result:[RAUtils base64en:[RAConvertor dict2string:ret]] module:url code:RESULT_NET_ERROR];
  160. }
  161. return jsonData;
  162. }
  163. else
  164. {
  165. // NSString* err_msg = [error localizedDescription];
  166. NSMutableString *str = [[NSMutableString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
  167. DebugLog(@"data string: %@",str);
  168. NSError *error1 = nil;
  169. NSMutableDictionary* jsobj = [[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error1] mutableCopy];
  170. if(jsobj==nil)// 服务器返回不是json
  171. {
  172. jsobj=[[NSMutableDictionary alloc] init];
  173. [jsobj setValue:[NSNumber numberWithInt:RESULT_NO_RESPONSE] forKey:@"result"];
  174. }
  175. if([jsobj[@"encrypt"] boolValue]==true)
  176. {
  177. jsobj = decryptBlock(jsobj);
  178. }
  179. if (resultBlock) {
  180. jsobj = resultBlock(jsobj);
  181. }
  182. int result=[[jsobj valueForKey:@"result"] intValue];
  183. if(![url isEqualToString:recorder_url]&&/*![url isEqualToString:URL_DOWNLOAD_OFFLINE]&&*/result!=2&&result!=99)
  184. {
  185. [self err_log:[RAUtils base64en:[RAConvertor dict2string:params]] result:[RAUtils base64en:str] module:url code:result];
  186. }
  187. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsobj
  188. options:0
  189. error:nil];
  190. return jsonData;
  191. }
  192. return responseData;
  193. }
  194. }
  195. +(NSDictionary*)err_log:(NSString*) up_params result:(NSString*)result module:(NSString*) module code:(int) code//device:(NSString*) device
  196. {
  197. // NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
  198. // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  199. // if(appDelegate.user!=nil)
  200. // [params setValue:appDelegate.user forKey:@"user"];
  201. //
  202. // [params setValue:up_params forKey:@"upparam"];
  203. //
  204. // [params setValue:[NSNumber numberWithInt:code ] forKey:@"code"];
  205. //
  206. // [params setValue:result forKey:@"result"];
  207. // [params setValue:module forKey:@"interfac"];
  208. //
  209. // [params setValue:[RAUtils base64en:[RAUtils dict2string: [RAUtils device_info]]] forKey:@"device"];
  210. //
  211. //
  212. // // [params setValue:module forKey:@"module"];
  213. //
  214. // // [[UIDevice currentDevice] name];
  215. //
  216. // // if(appDelegate.offline_mode)
  217. // // {
  218. // // return [OLDataProvider offline_notimpl];
  219. // // }
  220. // if(![self IsNetworkAvailable])
  221. // return [RAUtils error_json:RESULT_NET_NOTAVAILABLE err_msg:nil];
  222. //
  223. // NSData* json=[self get_json:URL_ERR_LOG parameters:params];
  224. // if(json==nil)
  225. // return nil;
  226. // NSError *error=nil;
  227. // NSDictionary *jsobj = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableLeaves error:&error];
  228. // return jsobj;
  229. // 子类没有处理err_log函数时的默认处理。
  230. NSMutableDictionary* jsobj = [@{@"result":@"2"} mutableCopy];
  231. return jsobj;
  232. }
  233. + (NSURLSessionTask *)upload:(NSData *)filedata FileName:(NSString*) filename Params:(NSDictionary *)params ToHost:(NSString *)urlString Result:(resultHandler)r Progress:(progressHandler)p DecryptHandler:(id (^)(NSString *))decrypt {
  234. // NSString *fileName = [filePath lastPathComponent];
  235. NSMutableData *dataM = [NSMutableData data];
  236. NSMutableString *stringM = [NSMutableString string];
  237. DebugLog(@"================parms==================");
  238. for (NSString *key in params) {
  239. [stringM appendString:[NSString stringWithFormat:@"--%@\r\n",BOUNDARY]];
  240. [stringM appendFormat:@"Content-Type: text/plain; charset=UTF-8\r\n"];
  241. [stringM appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
  242. [stringM appendFormat:@"%@\r\n",[params objectForKey:key]];
  243. DebugLog(@"parameter: key=%@ value=%@",key,[params objectForKey:key]);
  244. }
  245. DebugLog(@"================parms==================");
  246. // Apex Drivers 2018.5.5
  247. if (filedata) {
  248. [stringM appendString:[NSString stringWithFormat:@"--%@\r\n",BOUNDARY]];
  249. [stringM appendFormat:@"Content-Disposition: form-data; name=\"upfile\"; filename=%@\r\n",filename];
  250. [stringM appendString:@"Content-Type: application/mac-binary\r\n"];
  251. [stringM appendString:@"\r\n"];
  252. NSData *stringM_data = [stringM dataUsingEncoding:NSUTF8StringEncoding];
  253. [dataM appendData:stringM_data];
  254. // NSData *file_data = [NSData dataWithContentsOfFile:filePath];
  255. [dataM appendData:filedata];
  256. NSString *end = [NSString stringWithFormat:@"\r\n--%@--",BOUNDARY];
  257. [dataM appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
  258. } else {
  259. NSData *stringM_data = [stringM dataUsingEncoding:NSUTF8StringEncoding];
  260. [dataM appendData:stringM_data];
  261. NSString *end = [NSString stringWithFormat:@"\r\n--%@--",BOUNDARY];
  262. [dataM appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
  263. }
  264. // Data
  265. NSData *data = dataM;
  266. // 可变请求
  267. NSURL *url = [NSURL URLWithString:urlString];
  268. NSMutableURLRequest *requestM = [NSMutableURLRequest requestWithURL:url
  269. cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:JSON_TIMEOUT];
  270. // line note
  271. requestM.HTTPMethod = @"POST";
  272. // request header
  273. [requestM addValue:@"close" forHTTPHeaderField:@"Connection"];
  274. [requestM addValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",BOUNDARY] forHTTPHeaderField:@"Content-Type"];
  275. [requestM addValue:@"multipart/form-data" forHTTPHeaderField:@"enctype"];
  276. [requestM addValue:[NSString stringWithFormat:@"%lu", (unsigned long)[data length]] forHTTPHeaderField:@"Content-Length"];
  277. // request body
  278. requestM.HTTPBody = data;
  279. NSURLSession *urlSession = [self standSession];
  280. if (urlSession.delegate) {
  281. if ([urlSession.delegate isKindOfClass:[RANetworkTaskDelegate class]]) {
  282. RANetworkTaskDelegate *delegate = (RANetworkTaskDelegate *)urlSession.delegate;
  283. if (p) {
  284. delegate.p = p;
  285. }
  286. if (r) {
  287. delegate.r = r;
  288. }
  289. if (decrypt) {
  290. delegate.decryptHandler = decrypt;
  291. }
  292. }
  293. }
  294. NSURLSessionDataTask *dataTask = [urlSession uploadTaskWithRequest:requestM fromData:data];
  295. [dataTask resume];
  296. return dataTask;
  297. }
  298. + (NSURLSessionTask *)upload:(NSString *)filePath Params:(NSDictionary *)params ToHost:(NSString *)urlString Result:(resultHandler)r Progress:(progressHandler)p DecryptHandler:(id (^)(NSString *))decrypt {
  299. NSString *fileName = [filePath lastPathComponent];
  300. NSData *file_data = [NSData dataWithContentsOfFile:filePath];
  301. return [self upload:file_data FileName:fileName Params:params ToHost:urlString Result:r Progress:p DecryptHandler:decrypt];
  302. //
  303. // NSMutableData *dataM = [NSMutableData data];
  304. //
  305. // NSMutableString *stringM = [NSMutableString string];
  306. //
  307. //
  308. // DebugLog(@"================parms==================");
  309. //
  310. //
  311. //
  312. // for (NSString *key in params) {
  313. //
  314. // [stringM appendString:[NSString stringWithFormat:@"--%@\r\n",BOUNDARY]];
  315. // [stringM appendFormat:@"Content-Type: text/plain; charset=UTF-8\r\n"];
  316. // [stringM appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
  317. // [stringM appendFormat:@"%@\r\n",[params objectForKey:key]];
  318. //
  319. //
  320. // DebugLog(@"parameter: key=%@ value=%@",key,[params objectForKey:key]);
  321. // }
  322. // DebugLog(@"================parms==================");
  323. // [stringM appendString:[NSString stringWithFormat:@"--%@\r\n",BOUNDARY]];
  324. //
  325. // [stringM appendFormat:@"Content-Disposition: form-data; name=\"upfile\"; filename=%@\r\n",fileName];
  326. // [stringM appendString:@"Content-Type: application/mac-binary\r\n"];
  327. // [stringM appendString:@"\r\n"];
  328. //
  329. // NSData *stringM_data = [stringM dataUsingEncoding:NSUTF8StringEncoding];
  330. // [dataM appendData:stringM_data];
  331. //
  332. // NSData *file_data = [NSData dataWithContentsOfFile:filePath];
  333. // [dataM appendData:file_data];
  334. //
  335. // NSString *end = [NSString stringWithFormat:@"\r\n--%@--",BOUNDARY];
  336. // [dataM appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
  337. //
  338. // // Data
  339. // NSData *data = dataM;
  340. //
  341. //
  342. // // 可变请求
  343. // NSURL *url = [NSURL URLWithString:urlString];
  344. // NSMutableURLRequest *requestM = [NSMutableURLRequest requestWithURL:url
  345. // cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:JSON_TIMEOUT];
  346. // // line note
  347. // requestM.HTTPMethod = @"POST";
  348. //
  349. // // request header
  350. // [requestM addValue:@"close" forHTTPHeaderField:@"Connection"];
  351. //
  352. // [requestM addValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",BOUNDARY] forHTTPHeaderField:@"Content-Type"];
  353. //
  354. // [requestM addValue:[NSString stringWithFormat:@"%lu", (unsigned long)[data length]] forHTTPHeaderField:@"Content-Length"];
  355. //
  356. // // request body
  357. // requestM.HTTPBody = data;
  358. //
  359. //
  360. //
  361. // NSURLSession *urlSession = [self standSession];
  362. //
  363. // if (urlSession.delegate) {
  364. // if ([urlSession.delegate isKindOfClass:[RANetworkTaskDelegate class]]) {
  365. //
  366. // RANetworkTaskDelegate *delegate = (RANetworkTaskDelegate *)urlSession.delegate;
  367. //
  368. // if (p) {
  369. // delegate.p = p;
  370. // }
  371. //
  372. // if (r) {
  373. // delegate.r = r;
  374. // }
  375. //
  376. // if (decrypt) {
  377. // delegate.decryptHandler = decrypt;
  378. // }
  379. //
  380. // }
  381. // }
  382. //
  383. // NSURLSessionDataTask *dataTask = [urlSession uploadTaskWithRequest:requestM fromData:data];
  384. //
  385. // [dataTask resume];
  386. //
  387. // return dataTask;
  388. }
  389. + (NSURLSession *)standSession {
  390. NSURLSession *session = nil;
  391. RANetworkTaskDelegate *delegate = [RANetworkTaskDelegate sharedInstance];
  392. NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
  393. config.timeoutIntervalForRequest = JSON_TIMEOUT;
  394. NSOperationQueue *queue = [[NSOperationQueue alloc] init];
  395. session = [NSURLSession sessionWithConfiguration:config delegate:delegate delegateQueue:queue];
  396. return session;
  397. }
  398. + (NSURLSessionDataTask *)downloadFileOffset:(NSUInteger)offset Param:(NSDictionary *)param from:(NSString *)url method:(NSString *)method toPath:(NSString *)path progressHandler:(progressHandler)progressHandler completionHandler:(resultHandler)result {
  399. NSURLSession *sessoin = [self standSession];
  400. RANetworkTaskDelegate *delegate = (RANetworkTaskDelegate *)sessoin.delegate;
  401. delegate.downloadTask = YES;
  402. delegate.fileCachePath = path;
  403. if (progressHandler) {
  404. delegate.p = progressHandler;
  405. }
  406. if (result) {
  407. delegate.r = result;
  408. }
  409. NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
  410. req.HTTPMethod = method;
  411. if (offset > 0) {
  412. [req addValue:[NSString stringWithFormat:@"bytes=%ld-",(unsigned long)offset] forHTTPHeaderField:@"Range"];
  413. }
  414. // 拼接参数
  415. if (param && param.allValues.count > 0) {
  416. __block NSMutableArray *paramArr = [NSMutableArray array];
  417. [param enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
  418. [paramArr addObject:[NSString stringWithFormat:@"%@=%@",key,obj]];
  419. }];
  420. NSString *paramStr = [paramArr componentsJoinedByString:@"&"];
  421. req.HTTPBody = [paramStr dataUsingEncoding:NSUTF8StringEncoding];
  422. }
  423. NSURLSessionDataTask *downloadTask = [sessoin dataTaskWithRequest:req];
  424. [downloadTask resume];
  425. return downloadTask;
  426. }
  427. #pragma mark new interface
  428. +(NSMutableDictionary*) prepare_addtional_params:(NSMutableDictionary* ) params
  429. {
  430. //
  431. // NSString *userAction = [params valueForKey:kAction];
  432. // NSMutableDictionary *extra = [[params valueForKey:kExtra] mutableCopy];
  433. // if ([userAction isEqualToString:@"Login"]) {
  434. // if (!extra) {
  435. // extra = [NSMutableDictionary dictionary];
  436. // }
  437. // [extra setObject:[params objectForKey:@"user"] forKey:@"user"];
  438. // }
  439. return params;
  440. }
  441. +(NSData*)request_interface : (NSString*) url parameters:(NSMutableDictionary *) params err_record_url:(NSString* )recorder_url completionHandler:(resultHandler)result retry:(int) retry
  442. {
  443. // __block int retry = 0;
  444. if(![NetworkUtils IsNetworkAvailable])
  445. {
  446. dispatch_async(dispatch_get_main_queue(), ^{
  447. if(result)
  448. result([[RAConvertor string2dict:[NSString stringWithFormat:@"{'result':%d}",RESULT_NET_NOTAVAILABLE]] mutableCopy]);
  449. });
  450. // return detailContent;
  451. return nil;
  452. }
  453. params = [self prepare_addtional_params:params];
  454. //repeat:
  455. // {
  456. // return [self fake_json:url];
  457. // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  458. //分界线的标识符
  459. NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
  460. //根据url初始化request
  461. NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
  462. cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
  463. timeoutInterval:JSON_TIMEOUT];
  464. //分界线 --AaB03x
  465. NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
  466. //结束符 AaB03x--
  467. NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
  468. //要上传的图片
  469. // UIImage *image=[params objectForKey:@"pic"];
  470. //得到图片的data
  471. /*
  472. // NSData* data = [NSData dataWithContentsOfFile:file_path];
  473. */
  474. //http body的字符串
  475. NSMutableString *body=[[NSMutableString alloc]init];
  476. // NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
  477. // [params setValue:@"handset_login" forKey:@"action"];
  478. // [headers setValue:[NSString stringWithFormat:@"%d",dataLength] forKey:@"Content-Length"];
  479. // [params setValue:appDelegate.sessionid forKey:@"sessionid"];
  480. // [params setValue:password forKey:@"password"];
  481. // [params setValue:[NSString stringWithFormat:@"%d",ver] forKey:@"auth_ver"];
  482. // [headers setValue:headQuerlString forKey:@"param"];
  483. //参数的集合的所有key的集合
  484. NSArray *keys= [params allKeys];
  485. DebugLog(@"================parms==================");
  486. //遍历keys
  487. for(int i=0;i<[keys count];i++)
  488. {
  489. //得到当前key
  490. NSString *key=[keys objectAtIndex:i];
  491. //如果key不是pic,说明value是字符类型,比如name:Boris
  492. if(![key isEqualToString:@"pic"])
  493. {
  494. //添加分界线,换行
  495. [body appendFormat:@"%@\r\n",MPboundary];
  496. //添加字段名称,换2行
  497. [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
  498. //添加字段的值
  499. [body appendFormat:@"%@\r\n",[params objectForKey:key]];
  500. DebugLog(@"parameter: key=%@ value=%@",key,[params objectForKey:key]);
  501. }
  502. }
  503. DebugLog(@"================parms==================");
  504. ////添加分界线,换行
  505. /* [body appendFormat:@"%@\r\n",MPboundary];
  506. //声明pic字段,文件名为boris.png
  507. NSString * file_format=[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"upfile\"; filename=\"%@\"\r\n", [file_path lastPathComponent]];
  508. [body appendFormat:@"%@", file_format];
  509. //声明上传文件的格式
  510. [body appendFormat:@"Content-Type: application/zip\r\n\r\n"];
  511. */
  512. //声明结束符:--AaB03x--
  513. NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
  514. //声明myRequestData,用来放入http body
  515. NSMutableData *myRequestData=[NSMutableData data];
  516. //将body字符串转化为UTF8格式的二进制
  517. [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
  518. /*
  519. //将image的data加入
  520. [myRequestData appendData:data];
  521. */
  522. //加入结束符--AaB03x--
  523. [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
  524. //设置HTTPHeader中Content-Type的值
  525. NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
  526. //设置HTTPHeader
  527. [request setValue:content forHTTPHeaderField:@"Content-Type"];
  528. [request setValue:@"multipart/form-data" forHTTPHeaderField:@"enctype"];
  529. // 关闭keep alive
  530. [request setValue:@"close" forHTTPHeaderField:@"Connection"];
  531. //设置Content-Length
  532. [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
  533. //设置http body
  534. [request setHTTPBody:myRequestData];
  535. //http method
  536. [request setHTTPMethod:@"POST"];
  537. NSURLSession *urlSession = [self standSession];
  538. if (urlSession.delegate) {
  539. if ([urlSession.delegate isKindOfClass:[RANetworkTaskDelegate class]]) {
  540. RANetworkTaskDelegate *delegate = (RANetworkTaskDelegate *)urlSession.delegate;
  541. // if (p) {
  542. // delegate.p = p;
  543. // }
  544. //
  545. if (result) {
  546. delegate.r = result;
  547. }
  548. //
  549. // if (decrypt) {
  550. // delegate.decryptHandler = decrypt;
  551. // }
  552. }
  553. }
  554. NSURLSessionDataTask *dataTask =[urlSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  555. NSData *responseData =data;
  556. NSHTTPURLResponse* urlResponse =response;
  557. if (responseData==nil) {
  558. // DebugLog(@"response error:%@", [error localizedDescription]);
  559. NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
  560. //#define RESULT_FALSE 0
  561. //#define RESULT_TRUE 2
  562. //#define RESULT_NET_ERROR -3
  563. //#define RESULT_NET_NOTAVAILABLE -4
  564. //#define RESULT_ERROR -5
  565. //#define RESULT_LOCALFILE_ERROR -7
  566. //#define RESULT_USERAUTH_ERROR -9
  567. //#define RESULT_UPDATE_USERAUTH_ERROR -11
  568. //#define RESULT_SESSION_EXPIRED -13
  569. //#define RESULT_VER_LOW
  570. // NSString * moreinfo = error.description ;
  571. NSString* err_msg = [error localizedDescription];
  572. //-----------------retry 3 times for error code -1005------------------------
  573. if(error.code==-1005&&retry<3)
  574. {
  575. int new_retry=retry+1;
  576. [self request_interface:url parameters:params err_record_url:recorder_url completionHandler:result retry:new_retry];
  577. return;
  578. // retry++;
  579. // goto repeat;
  580. }
  581. //-----------------end retry 3 times for error code -1005------------------------
  582. NSDictionary* error_json = [RAUtils error_dict:error];
  583. [ret setObject:error_json forKey:@"err_obj"];
  584. NSString* resp_msg= nil;
  585. if(err_msg.length==0)
  586. {
  587. err_msg =[NSHTTPURLResponse localizedStringForStatusCode:urlResponse.statusCode];
  588. resp_msg = err_msg;
  589. }
  590. [ret setValue:[NSString stringWithFormat:@"%d",RESULT_NET_ERROR] forKey:@"result"];
  591. [ret setValue:err_msg forKey:@"err_msg"];
  592. [ret setValue:resp_msg forKey:@"resp_msg"];
  593. [ret setValue:[NSString stringWithFormat:@"%ld",(long)urlResponse.statusCode] forKey:@"resp_code"];
  594. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ret
  595. options:0
  596. error:nil];
  597. if(![url isEqualToString:recorder_url])
  598. {
  599. [self err_log:[RAUtils base64en:[RAConvertor dict2string:params]] result:[RAUtils base64en:[RAConvertor dict2string:ret]] module:url code:RESULT_NET_ERROR];
  600. }
  601. dispatch_async(dispatch_get_main_queue(), ^{
  602. if(result)
  603. return result([[RAConvertor data2dict:jsonData] mutableCopy]);
  604. });
  605. }
  606. else
  607. {
  608. NSDictionary* dict =[RAConvertor data2dict:responseData];
  609. dispatch_async(dispatch_get_main_queue(), ^{
  610. if(result)
  611. return result([[RAConvertor data2dict:responseData] mutableCopy]);
  612. });
  613. }
  614. }];
  615. // NSURLSessionDataTask *dataTask = [urlSession dataTaskWithRequest:request ];
  616. [dataTask resume];
  617. return nil;
  618. //
  619. //
  620. // NSHTTPURLResponse* urlResponse = nil;
  621. //
  622. // NSError *error = nil;
  623. // NSLog(@"begin request %@",url);
  624. //
  625. // NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
  626. //
  627. //
  628. // DebugLog(@"url: %@",url);
  629. //
  630. // DebugLog(@"response: %@",[NSHTTPURLResponse localizedStringForStatusCode:urlResponse.statusCode]);
  631. //
  632. //
  633. // NSLog(@"get response");
  634. // if (responseData==nil) {
  635. //
  636. // // DebugLog(@"response error:%@", [error localizedDescription]);
  637. //
  638. //
  639. // NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
  640. // //#define RESULT_FALSE 0
  641. // //#define RESULT_TRUE 2
  642. // //#define RESULT_NET_ERROR -3
  643. // //#define RESULT_NET_NOTAVAILABLE -4
  644. // //#define RESULT_ERROR -5
  645. // //#define RESULT_LOCALFILE_ERROR -7
  646. // //#define RESULT_USERAUTH_ERROR -9
  647. // //#define RESULT_UPDATE_USERAUTH_ERROR -11
  648. // //#define RESULT_SESSION_EXPIRED -13
  649. // //#define RESULT_VER_LOW
  650. //
  651. // // NSString * moreinfo = error.description ;
  652. //
  653. // NSString* err_msg = [error localizedDescription];
  654. //
  655. //
  656. // //-----------------retry 3 times for error code -1005------------------------
  657. // if(error.code==-1005&&retry<3)
  658. // {
  659. // retry++;
  660. // goto repeat;
  661. //
  662. // }
  663. // //-----------------end retry 3 times for error code -1005------------------------
  664. //
  665. // NSDictionary* error_json = [RAUtils error_dict:error];
  666. // [ret setObject:error_json forKey:@"err_obj"];
  667. // NSString* resp_msg= nil;
  668. //
  669. // if(err_msg.length==0)
  670. // {
  671. // err_msg =[NSHTTPURLResponse localizedStringForStatusCode:urlResponse.statusCode];
  672. // resp_msg = err_msg;
  673. // }
  674. // [ret setValue:[NSString stringWithFormat:@"%d",RESULT_NET_ERROR] forKey:@"result"];
  675. // [ret setValue:err_msg forKey:@"err_msg"];
  676. // [ret setValue:resp_msg forKey:@"resp_msg"];
  677. // [ret setValue:[NSString stringWithFormat:@"%ld",(long)urlResponse.statusCode] forKey:@"resp_code"];
  678. //
  679. //
  680. // NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ret
  681. // options:0
  682. // error:nil];
  683. // if(![url isEqualToString:recorder_url])
  684. // {
  685. // [self err_log:[RAUtils base64en:[RAConvertor dict2string:params]] result:[RAUtils base64en:[RAConvertor dict2string:ret]] module:url code:RESULT_NET_ERROR];
  686. // }
  687. // return jsonData;
  688. //
  689. // }
  690. // else
  691. // {
  692. // // NSString* err_msg = [error localizedDescription];
  693. // NSMutableString *str = [[NSMutableString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
  694. //
  695. // DebugLog(@"data string: %@",str);
  696. // NSError *error1 = nil;
  697. //
  698. // NSMutableDictionary* jsobj = [[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error1] mutableCopy];
  699. //
  700. // if(jsobj==nil)// 服务器返回不是json
  701. // {
  702. //
  703. // jsobj=[[NSMutableDictionary alloc] init];
  704. // [jsobj setValue:[NSNumber numberWithInt:RESULT_NO_RESPONSE] forKey:@"result"];
  705. //
  706. // }
  707. //// if([jsobj[@"encrypt"] boolValue]==true)
  708. //// {
  709. //// jsobj = decryptBlock(jsobj);
  710. //// }
  711. //// if (resultBlock) {
  712. //// jsobj = resultBlock(jsobj);
  713. //// }
  714. //
  715. // int result=[[jsobj valueForKey:@"result"] intValue];
  716. // if(![url isEqualToString:recorder_url]&&/*![url isEqualToString:URL_DOWNLOAD_OFFLINE]&&*/result!=2&&result!=99)
  717. // {
  718. // [self err_log:[RAUtils base64en:[RAConvertor dict2string:params]] result:[RAUtils base64en:str] module:url code:result];
  719. // }
  720. // NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsobj
  721. // options:0
  722. // error:nil];
  723. // return jsonData;
  724. //
  725. // }
  726. // return responseData;
  727. // }
  728. }
  729. +(NSData*)request_file : (NSString*) url parameters:(NSMutableDictionary *) params err_record_url:(NSString* )recorder_url completionHandler:(resultHandler)result
  730. /* dataHandler:(dataHandler)returndata*/
  731. {
  732. // __block int retry = 0;
  733. if(![NetworkUtils IsNetworkAvailable])
  734. {
  735. dispatch_async(dispatch_get_main_queue(), ^{
  736. if(result)
  737. result([[RAConvertor string2dict:[NSString stringWithFormat:@"{'result':%d}",RESULT_NET_NOTAVAILABLE]] mutableCopy]);
  738. });
  739. // return detailContent;
  740. return nil;
  741. }
  742. params = [self prepare_addtional_params:params];
  743. //repeat:
  744. // {
  745. // return [self fake_json:url];
  746. // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  747. //分界线的标识符
  748. NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
  749. //根据url初始化request
  750. NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
  751. cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
  752. timeoutInterval:JSON_TIMEOUT];
  753. //分界线 --AaB03x
  754. NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
  755. //结束符 AaB03x--
  756. NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
  757. //要上传的图片
  758. // UIImage *image=[params objectForKey:@"pic"];
  759. //得到图片的data
  760. /*
  761. // NSData* data = [NSData dataWithContentsOfFile:file_path];
  762. */
  763. //http body的字符串
  764. NSMutableString *body=[[NSMutableString alloc]init];
  765. // NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
  766. // [params setValue:@"handset_login" forKey:@"action"];
  767. // [headers setValue:[NSString stringWithFormat:@"%d",dataLength] forKey:@"Content-Length"];
  768. // [params setValue:appDelegate.sessionid forKey:@"sessionid"];
  769. // [params setValue:password forKey:@"password"];
  770. // [params setValue:[NSString stringWithFormat:@"%d",ver] forKey:@"auth_ver"];
  771. // [headers setValue:headQuerlString forKey:@"param"];
  772. //参数的集合的所有key的集合
  773. NSArray *keys= [params allKeys];
  774. DebugLog(@"================parms==================");
  775. //遍历keys
  776. for(int i=0;i<[keys count];i++)
  777. {
  778. //得到当前key
  779. NSString *key=[keys objectAtIndex:i];
  780. //如果key不是pic,说明value是字符类型,比如name:Boris
  781. if(![key isEqualToString:@"pic"])
  782. {
  783. //添加分界线,换行
  784. [body appendFormat:@"%@\r\n",MPboundary];
  785. //添加字段名称,换2行
  786. [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
  787. //添加字段的值
  788. [body appendFormat:@"%@\r\n",[params objectForKey:key]];
  789. DebugLog(@"parameter: key=%@ value=%@",key,[params objectForKey:key]);
  790. }
  791. }
  792. DebugLog(@"================parms==================");
  793. ////添加分界线,换行
  794. /* [body appendFormat:@"%@\r\n",MPboundary];
  795. //声明pic字段,文件名为boris.png
  796. NSString * file_format=[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"upfile\"; filename=\"%@\"\r\n", [file_path lastPathComponent]];
  797. [body appendFormat:@"%@", file_format];
  798. //声明上传文件的格式
  799. [body appendFormat:@"Content-Type: application/zip\r\n\r\n"];
  800. */
  801. //声明结束符:--AaB03x--
  802. NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
  803. //声明myRequestData,用来放入http body
  804. NSMutableData *myRequestData=[NSMutableData data];
  805. //将body字符串转化为UTF8格式的二进制
  806. [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
  807. /*
  808. //将image的data加入
  809. [myRequestData appendData:data];
  810. */
  811. //加入结束符--AaB03x--
  812. [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
  813. //设置HTTPHeader中Content-Type的值
  814. NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
  815. //设置HTTPHeader
  816. [request setValue:content forHTTPHeaderField:@"Content-Type"];
  817. [request setValue:@"multipart/form-data" forHTTPHeaderField:@"enctype"];
  818. // 关闭keep alive
  819. [request setValue:@"close" forHTTPHeaderField:@"Connection"];
  820. //设置Content-Length
  821. [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
  822. //设置http body
  823. [request setHTTPBody:myRequestData];
  824. //http method
  825. [request setHTTPMethod:@"POST"];
  826. NSURLSession *urlSession = [self standSession];
  827. if (urlSession.delegate) {
  828. if ([urlSession.delegate isKindOfClass:[RANetworkTaskDelegate class]]) {
  829. RANetworkTaskDelegate *delegate = (RANetworkTaskDelegate *)urlSession.delegate;
  830. // if (p) {
  831. // delegate.p = p;
  832. // }
  833. //
  834. if (result) {
  835. delegate.r = result;
  836. }
  837. //
  838. // if (decrypt) {
  839. // delegate.decryptHandler = decrypt;
  840. // }
  841. }
  842. }
  843. NSURLSessionDownloadTask* downloadTask=[urlSession downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  844. NSHTTPURLResponse* urlResponse =response;
  845. NSData* data =[NSData dataWithContentsOfURL:location] ;
  846. NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
  847. if(data==nil)
  848. {
  849. NSString* err_msg = [error localizedDescription];
  850. NSDictionary* error_json = [RAUtils error_dict:error];
  851. [ret setObject:error_json forKey:@"err_obj"];
  852. NSString* resp_msg= nil;
  853. if(err_msg.length==0)
  854. {
  855. err_msg =[NSHTTPURLResponse localizedStringForStatusCode:urlResponse.statusCode];
  856. resp_msg = err_msg;
  857. }
  858. [ret setValue:[NSString stringWithFormat:@"%d",RESULT_NET_ERROR] forKey:@"result"];
  859. [ret setValue:err_msg forKey:@"err_msg"];
  860. [ret setValue:resp_msg forKey:@"resp_msg"];
  861. [ret setValue:[NSString stringWithFormat:@"%ld",(long)urlResponse.statusCode] forKey:@"resp_code"];
  862. dispatch_async(dispatch_get_main_queue(), ^{
  863. if(result)
  864. result(ret);
  865. });
  866. }
  867. else
  868. {
  869. ret[@"result"]=@"2";
  870. ret[@"data"]=data;
  871. ret[@"path"]=[location absoluteString];
  872. dispatch_async(dispatch_get_main_queue(), ^{
  873. if(result)
  874. result(ret);
  875. });
  876. }
  877. // if(returndata)
  878. // {
  879. // returndata(data);
  880. // }
  881. }];
  882. [downloadTask resume];
  883. return nil;
  884. //
  885. // NSURLSessionDataTask *dataTask =[urlSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  886. //
  887. // NSData *responseData =data;
  888. // NSHTTPURLResponse* urlResponse =response;
  889. // if (responseData==nil) {
  890. //
  891. // // DebugLog(@"response error:%@", [error localizedDescription]);
  892. //
  893. //
  894. // NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
  895. // //#define RESULT_FALSE 0
  896. // //#define RESULT_TRUE 2
  897. // //#define RESULT_NET_ERROR -3
  898. // //#define RESULT_NET_NOTAVAILABLE -4
  899. // //#define RESULT_ERROR -5
  900. // //#define RESULT_LOCALFILE_ERROR -7
  901. // //#define RESULT_USERAUTH_ERROR -9
  902. // //#define RESULT_UPDATE_USERAUTH_ERROR -11
  903. // //#define RESULT_SESSION_EXPIRED -13
  904. // //#define RESULT_VER_LOW
  905. //
  906. // // NSString * moreinfo = error.description ;
  907. //
  908. // NSString* err_msg = [error localizedDescription];
  909. //
  910. //
  911. // //-----------------retry 3 times for error code -1005------------------------
  912. // if(error.code==-1005&&retry<3)
  913. // {
  914. // int new_retry=retry+1;
  915. // [self request_interface:url parameters:params err_record_url:recorder_url completionHandler:result retry:new_retry];
  916. // return;
  917. // // retry++;
  918. // // goto repeat;
  919. //
  920. // }
  921. // //-----------------end retry 3 times for error code -1005------------------------
  922. //
  923. // NSDictionary* error_json = [RAUtils error_dict:error];
  924. // [ret setObject:error_json forKey:@"err_obj"];
  925. // NSString* resp_msg= nil;
  926. //
  927. // if(err_msg.length==0)
  928. // {
  929. // err_msg =[NSHTTPURLResponse localizedStringForStatusCode:urlResponse.statusCode];
  930. // resp_msg = err_msg;
  931. // }
  932. // [ret setValue:[NSString stringWithFormat:@"%d",RESULT_NET_ERROR] forKey:@"result"];
  933. // [ret setValue:err_msg forKey:@"err_msg"];
  934. // [ret setValue:resp_msg forKey:@"resp_msg"];
  935. // [ret setValue:[NSString stringWithFormat:@"%ld",(long)urlResponse.statusCode] forKey:@"resp_code"];
  936. //
  937. //
  938. // NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ret
  939. // options:0
  940. // error:nil];
  941. // if(![url isEqualToString:recorder_url])
  942. // {
  943. // [self err_log:[RAUtils base64en:[RAConvertor dict2string:params]] result:[RAUtils base64en:[RAConvertor dict2string:ret]] module:url code:RESULT_NET_ERROR];
  944. // }
  945. //
  946. // if(result)
  947. // return result([[RAConvertor data2dict:jsonData] mutableCopy]);
  948. //
  949. // }
  950. // else
  951. // {
  952. // NSDictionary* dict =[RAConvertor data2dict:responseData];
  953. // dispatch_async(dispatch_get_main_queue(), ^{
  954. // if(result)
  955. // return result([[RAConvertor data2dict:responseData] mutableCopy]);
  956. // });
  957. //
  958. // }
  959. //
  960. // }];
  961. //// NSURLSessionDataTask *dataTask = [urlSession dataTaskWithRequest:request ];
  962. //
  963. // [dataTask resume];
  964. //
  965. // return nil;
  966. //
  967. //
  968. // NSHTTPURLResponse* urlResponse = nil;
  969. //
  970. // NSError *error = nil;
  971. // NSLog(@"begin request %@",url);
  972. //
  973. // NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
  974. //
  975. //
  976. // DebugLog(@"url: %@",url);
  977. //
  978. // DebugLog(@"response: %@",[NSHTTPURLResponse localizedStringForStatusCode:urlResponse.statusCode]);
  979. //
  980. //
  981. // NSLog(@"get response");
  982. // if (responseData==nil) {
  983. //
  984. // // DebugLog(@"response error:%@", [error localizedDescription]);
  985. //
  986. //
  987. // NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
  988. // //#define RESULT_FALSE 0
  989. // //#define RESULT_TRUE 2
  990. // //#define RESULT_NET_ERROR -3
  991. // //#define RESULT_NET_NOTAVAILABLE -4
  992. // //#define RESULT_ERROR -5
  993. // //#define RESULT_LOCALFILE_ERROR -7
  994. // //#define RESULT_USERAUTH_ERROR -9
  995. // //#define RESULT_UPDATE_USERAUTH_ERROR -11
  996. // //#define RESULT_SESSION_EXPIRED -13
  997. // //#define RESULT_VER_LOW
  998. //
  999. // // NSString * moreinfo = error.description ;
  1000. //
  1001. // NSString* err_msg = [error localizedDescription];
  1002. //
  1003. //
  1004. // //-----------------retry 3 times for error code -1005------------------------
  1005. // if(error.code==-1005&&retry<3)
  1006. // {
  1007. // retry++;
  1008. // goto repeat;
  1009. //
  1010. // }
  1011. // //-----------------end retry 3 times for error code -1005------------------------
  1012. //
  1013. // NSDictionary* error_json = [RAUtils error_dict:error];
  1014. // [ret setObject:error_json forKey:@"err_obj"];
  1015. // NSString* resp_msg= nil;
  1016. //
  1017. // if(err_msg.length==0)
  1018. // {
  1019. // err_msg =[NSHTTPURLResponse localizedStringForStatusCode:urlResponse.statusCode];
  1020. // resp_msg = err_msg;
  1021. // }
  1022. // [ret setValue:[NSString stringWithFormat:@"%d",RESULT_NET_ERROR] forKey:@"result"];
  1023. // [ret setValue:err_msg forKey:@"err_msg"];
  1024. // [ret setValue:resp_msg forKey:@"resp_msg"];
  1025. // [ret setValue:[NSString stringWithFormat:@"%ld",(long)urlResponse.statusCode] forKey:@"resp_code"];
  1026. //
  1027. //
  1028. // NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ret
  1029. // options:0
  1030. // error:nil];
  1031. // if(![url isEqualToString:recorder_url])
  1032. // {
  1033. // [self err_log:[RAUtils base64en:[RAConvertor dict2string:params]] result:[RAUtils base64en:[RAConvertor dict2string:ret]] module:url code:RESULT_NET_ERROR];
  1034. // }
  1035. // return jsonData;
  1036. //
  1037. // }
  1038. // else
  1039. // {
  1040. // // NSString* err_msg = [error localizedDescription];
  1041. // NSMutableString *str = [[NSMutableString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
  1042. //
  1043. // DebugLog(@"data string: %@",str);
  1044. // NSError *error1 = nil;
  1045. //
  1046. // NSMutableDictionary* jsobj = [[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error1] mutableCopy];
  1047. //
  1048. // if(jsobj==nil)// 服务器返回不是json
  1049. // {
  1050. //
  1051. // jsobj=[[NSMutableDictionary alloc] init];
  1052. // [jsobj setValue:[NSNumber numberWithInt:RESULT_NO_RESPONSE] forKey:@"result"];
  1053. //
  1054. // }
  1055. //// if([jsobj[@"encrypt"] boolValue]==true)
  1056. //// {
  1057. //// jsobj = decryptBlock(jsobj);
  1058. //// }
  1059. //// if (resultBlock) {
  1060. //// jsobj = resultBlock(jsobj);
  1061. //// }
  1062. //
  1063. // int result=[[jsobj valueForKey:@"result"] intValue];
  1064. // if(![url isEqualToString:recorder_url]&&/*![url isEqualToString:URL_DOWNLOAD_OFFLINE]&&*/result!=2&&result!=99)
  1065. // {
  1066. // [self err_log:[RAUtils base64en:[RAConvertor dict2string:params]] result:[RAUtils base64en:str] module:url code:result];
  1067. // }
  1068. // NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsobj
  1069. // options:0
  1070. // error:nil];
  1071. // return jsonData;
  1072. //
  1073. // }
  1074. // return responseData;
  1075. // }
  1076. }
  1077. @end