您的位置:首页 > 移动开发 > IOS开发

iOS-GET请求详细操作-GET设置请求头

2016-03-04 12:12 671 查看
难得一次备注相当详细的原生GET网络请求操作,强迫症一样记录下来和大家分享… 也备复制用

-(void)getResult{

_MB = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];

//接口路径
NSString *path = @"http://a.apix.cn/apixlife/phone/phone";

//路径-+参数
NSString *pathWithPhoneNum = [NSString stringWithFormat:@"%@?phone=%@",path,_phoneNumFD.text];

//中文编码
NSString *urlPath = [pathWithPhoneNum stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

//URL
NSURL *phoneURL = [NSURL URLWithString:urlPath];

//请求对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:phoneURL];

//请求方式
[request setHTTPMethod:@"GET"];

//请求头
[request setValue:@"92b5787ecd17417b718a2aaedc7e6ce8" forHTTPHeaderField:@"apix-key"];

//网络配置
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];

//网络会话
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];

//任务
NSURLSessionDataTask *sessionTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

//回到主线程更新UI -> 撤销遮罩
dispatch_async(dispatch_get_main_queue(), ^{
[_MB hide:YES];
});

if (error) {
NSLog(@"请求失败... %@",error);

//提示用户请求失败!
UIAlertController *AV = [UIAlertController alertControllerWithTitle:@"提示" message:@"抱歉,服务器错误,请稍后重试..." preferredStyle:UIAlertControllerStyleActionSheet];
[AV addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//点击OK,进行相应操作,可置nil
NSLog(@"您点击了OK..");
}]];
[self presentViewController:AV animated:YES completion:nil];

}else{
//JSON 解析 苹果原生效率最高
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
if ([[result objectForKey:@"message"] isEqualToString:@"success"]) {
//获取数据->主线程更新UI
dispatch_async(dispatch_get_main_queue(), ^{
NSDictionary *data = [result objectForKey:@"data"];
NSString *city = [data objectForKey:@"city"];
NSString *province = [data objectForKey:@"province"];
NSString *belong = [NSString stringWithFormat:@"%@ · %@",province,city];
[_resultLB setText:belong];
});
}else{
NSLog(@"未查到信息....");
}
NSLog(@"请求成功... %@",result);
}
}];

//开始任务
[sessionTask resume];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: