NetworkUtils.m 73 KB

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