本文主要記錄筆者在ios7之前后所用的數(shù)據(jù)請(qǐng)求方式匣摘,以及現(xiàn)在常用到的AFN數(shù)據(jù)請(qǐng)求的封裝(本文依然是筆者作為筆記使用,如有錯(cuò)誤的地方還望指正熊响,共同學(xué)習(xí))
1.請(qǐng)求(同步)
// 1.獲取URl字符串
? ? //? NSString *urlString = KUrl;
? ? // 2.將URL字符串轉(zhuǎn)化成NSURL對(duì)象
? ? NSURL *url = [NSURL URLWithString:KUrl];
? // 3.創(chuàng)建請(qǐng)求對(duì)象
? ? // 如果沒(méi)有網(wǎng)絡(luò)缠捌,直接return 不再請(qǐng)求數(shù)據(jù)
? //? if (![[NetWorkState shareInstance]reachability]) {
? ? ? //? return;
? //? }
? ? NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
? ? // 4.1.設(shè)置請(qǐng)求方式 默認(rèn)是GEt請(qǐng)求
? ? [request setHTTPMethod:@"GET"];
? 4.2 設(shè)置POST請(qǐng)求的樣式
[request setHTTPMethod:@"POST"];
? [request setHTTPBody:postData]; // postData 是數(shù)據(jù)請(qǐng)求的參數(shù)
? ? // 5.創(chuàng)建同步鏈接
? ? NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
? // NSLog(@"%@",data);
? ? // 6.根據(jù)請(qǐng)求下來(lái)的data 解析data
? ? id ?dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
2.異步請(qǐng)求
方式1中的第五步之前所有代碼一樣
5.1 ?將當(dāng)前類設(shè)為代理患朱,進(jìn)行異步的數(shù)據(jù)請(qǐng)求
[NSURLConnection connectionWithRequest:request delegate:self];
#pragma mark ---------當(dāng)服務(wù)器開(kāi)始請(qǐng)求調(diào)用的方法 ------------
// 向服務(wù)器發(fā)送請(qǐng)求 服務(wù)器有響應(yīng)之后會(huì)調(diào)用此方法
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
? ? self.receiveData = [NSMutableData data];
?? NSLog(@"服務(wù)器有相應(yīng)");
}
#pragma mark -------- 當(dāng)服務(wù)器開(kāi)始傳輸?shù)臅r(shí)候 ------------
//此方法中 我們要進(jìn)行拼接數(shù)據(jù) 此方法會(huì)根據(jù)數(shù)據(jù)的大小 執(zhí)行不定的次數(shù) 直到所有數(shù)據(jù)拼接完成
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
? ? [self.receiveData appendData:data];
? ? NSLog(@"服務(wù)器開(kāi)始傳輸數(shù)據(jù)");
}
#pragma mark --------當(dāng)服務(wù)器結(jié)束傳輸?shù)臅r(shí)候 ---------
// 相當(dāng)于 傳輸數(shù)據(jù)完畢 我們已經(jīng)拿到了所有的data 再次方法中解析數(shù)據(jù)
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
? ? NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.receiveData options:NSJSONReadingMutableContainers error:nil]
? ? [self.tableView reloadData];
? ? NSLog(@"服務(wù)器結(jié)束傳輸數(shù)據(jù)");
}
#pragma mark -----------請(qǐng)求失敗 ------------
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
? ?NSLog(@"請(qǐng)求失敗");
}
5.2 block請(qǐng)求(不常用)
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
? ? ? ? NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
? ? ? ? blockSelf.dataArray = [Model jsonConfigue:dic];
// 進(jìn)行頁(yè)面的刷新 ? ? ? ?[blockSelf.tableView reloadData];
? ? }];
3,ios7 之后旭斥,蘋(píng)果新出了一個(gè)NSURLSession類來(lái)進(jìn)行數(shù)據(jù)請(qǐng)求
NSURL *url = [NSURL URLWithString:urlString];
1.//初始化request 并配置httpBody httpMethod
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:30];
// post請(qǐng)求
request.HTTPBody = [@"postData" dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPMethod = @"POST";
// get請(qǐng)求
request.HTTPMethod = @"GET";
2 //配置session 并讓task開(kāi)始執(zhí)行
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
? ? ? ? NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
}];
[task resume];
4.AFN的封裝
? ? if ([self isNetWorkConnectAvailiable]) {
? ? // 創(chuàng)建一個(gè)請(qǐng)求對(duì)象
? ? AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
? ? // 請(qǐng)求https
? ? ? // [manager setSecurityPolicy:securityPolicy];
? ? ? ? manager.securityPolicy.allowInvalidCertificates = YES;
? ? ? ? manager.securityPolicy.validatesDomainName = NO;
? ?// 設(shè)置請(qǐng)求格式
? ? manager.requestSerializer = [AFHTTPRequestSerializer serializer];
? // 設(shè)置響應(yīng)格式
? ? manager.responseSerializer = [AFHTTPResponseSerializer serializer];
? ? ? ? // manager.requestSerializer = [AFJSONRequestSerializer new];
?? ?// 設(shè)置超時(shí)時(shí)間
? ? ? ? manager.requestSerializer.timeoutInterval = 20.0f;
? ? // 響應(yīng)的類型
? ? [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/css", @"text/plain",@"application/x-javascript",@"text/xml", nil]];
? ? // 設(shè)置頭
? ? ? ? if (![url isEqualToString:ZGR_LOGIN]) {
? ? ? ? ? ? [manager.requestSerializer setValue:[[NSUserDefaults standardUserDefaults] valueForKey:@"httpHeader"] forHTTPHeaderField:@"headpost"];
? ? ? ? }
? ? ? ?NSLog(@"-=-=-%@",manager.requestSerializer.HTTPRequestHeaders);
? // UIView *view = [[UIApplication sharedApplication].delegate window];
? ? ? ? MBProgressHUD *hud = [[MBProgressHUD alloc]init];
? ? ? ? if (hudView) {
? ? ? ? ? hud = [MBProgressHUD showHUDAddedTo:hudView animated:YES];
? ? ? ? }
? ? ? hud.backgroundColor = [UIColor whiteColor];
? ?hud.mode = MBProgressHUDModeIndeterminate;
? ? ? ?[manager POST:url parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id? _Nonnull responseObject) {
? ? ? ? ? ? if ([dic isKindOfClass:[NSString class]]) {
? ? ? ? ? ? ? ? id result = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
? ? ? ? ? ? ? ?[hud hideAnimated:YES];
? ? ? ? ? ? ? ? block(result);
? ? ? ? ? ? }
? ? ? ? ? ? else
? ? ? ? ? ? {
? ? ? ? ? ? id result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
? ? ? ? ? ?[hud hideAnimated:YES];
? ? ? ? ? ? block(result);
? ? ? ? ? ? }
? ? ? ? } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
? ? ? ? ? ? hud.label.text = @"加載失敗,請(qǐng)檢查網(wǎng)絡(luò)";
? ? ? ? ? ? //? [hud hideAnimated:YES afterDelay:0.5];
? ? ? ? ? ? failureBlock(error);
? ? ? ? }];
? ? }
? ? else
? ? {
? ? UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"無(wú)網(wǎng)絡(luò)連接, 請(qǐng)重新檢查網(wǎng)絡(luò)" delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil, nil];
? ? ? ? alert.delegate = self;
? ? ? ? [alert show];
? ? ? ? failureBlock(nil);
? ? }
本文是筆者對(duì)先前所用到的數(shù)據(jù)請(qǐng)求方式的總結(jié)記錄容达,若有錯(cuò)誤的地方,請(qǐng)指正