本文主要记录笔者在ios7之前后所用的数据请求方式,以及现在常用到的AFN数据请求的封装(本文依然是笔者作为笔记使用,如有错误的地方还望指正,共同学习)
1.请求(同步)
// 1.获取URl字符串
// NSString *urlString = KUrl;
// 2.将URL字符串转化成NSURL对象
NSURL *url = [NSURL URLWithString:KUrl];
// 3.创建请求对象
// 如果没有网络,直接return 不再请求数据
// if (![[NetWorkState shareInstance]reachability]) {
// return;
// }
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
// 4.1.设置请求方式 默认是GEt请求
[request setHTTPMethod:@"GET"];
4.2 设置POST请求的样式
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData]; // postData 是数据请求的参数
// 5.创建同步链接
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// NSLog(@"%@",data);
// 6.根据请求下来的data 解析data
id dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
2.异步请求
方式1中的第五步之前所有代码一样
5.1 将当前类设为代理,进行异步的数据请求
[NSURLConnection connectionWithRequest:request delegate:self];
#pragma mark ---------当服务器开始请求调用的方法 ------------
// 向服务器发送请求 服务器有响应之后会调用此方法
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
self.receiveData = [NSMutableData data];
NSLog(@"服务器有相应");
}
#pragma mark -------- 当服务器开始传输的时候 ------------
//此方法中 我们要进行拼接数据 此方法会根据数据的大小 执行不定的次数 直到所有数据拼接完成
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.receiveData appendData:data];
NSLog(@"服务器开始传输数据");
}
#pragma mark --------当服务器结束传输的时候 ---------
// 相当于 传输数据完毕 我们已经拿到了所有的data 再次方法中解析数据
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.receiveData options:NSJSONReadingMutableContainers error:nil]
[self.tableView reloadData];
NSLog(@"服务器结束传输数据");
}
#pragma mark -----------请求失败 ------------
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"请求失败");
}
5.2 block请求(不常用)
[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];
// 进行页面的刷新 [blockSelf.tableView reloadData];
}];
3,ios7 之后,苹果新出了一个NSURLSession类来进行数据请求
NSURL *url = [NSURL URLWithString:urlString];
1.//初始化request 并配置httpBody httpMethod
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:30];
// post请求
request.HTTPBody = [@"postData" dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPMethod = @"POST";
// get请求
request.HTTPMethod = @"GET";
2 //配置session 并让task开始执行
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]) {
// 创建一个请求对象
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
// 请求https
// [manager setSecurityPolicy:securityPolicy];
manager.securityPolicy.allowInvalidCertificates = YES;
manager.securityPolicy.validatesDomainName = NO;
// 设置请求格式
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
// 设置响应格式
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
// manager.requestSerializer = [AFJSONRequestSerializer new];
// 设置超时时间
manager.requestSerializer.timeoutInterval = 20.0f;
// 响应的类型
[manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/css", @"text/plain",@"application/x-javascript",@"text/xml", nil]];
// 设置头
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 = @"加载失败,请检查网络";
// [hud hideAnimated:YES afterDelay:0.5];
failureBlock(error);
}];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"无网络连接, 请重新检查网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
alert.delegate = self;
[alert show];
failureBlock(nil);
}
本文是笔者对先前所用到的数据请求方式的总结记录,若有错误的地方,请指正