NSURLConnection的使用
一:NSURLConnection(IOS9.0已经弃用)是早期apple提供的http访问方式。以下列出了常用的几个场景:GET请求,POST请求,Response中带有json数据
对于NSURLConnection有以下注意事项:(1)sendAsynchronourequest: queue: completionHandler:函数中的queue参数表示的是“handler 这个block运行在queue中,如果queue为mainThread,那么hanlder就运行在主线程;所以在处理UI的时候需要注意这个参数”
(1)Get请求(返回文本)
//RequestNSMutableURLRequest *urlRequest = [NSMutableURLRequest new]; [urlRequest setURL:[NSURL URLWithString:@"http://XXX.sinaapp.com/test/test.php?namr&id=43"]];[urlRequest setTimeoutInterval:10.0f];[urlRequest setHTTPMethod:@"GET"];[urlRequest setCachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData];NSOperationQueue *queue = [[NSOperationQueue alloc]init];[NSURLConnection sendAsynchronousRequest:urlRequestqueue:queuecompletionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { //根据回复Headers,确认是是否为NSHTTPURLResponse的对象if([response isKindOfClass:[NSHTTPURLResponse class]]){NSHTTPURLResponse *resHttp = (NSHTTPURLResponse *)response;NSLog(@"status = %ld",resHttp.statusCode);//200 304 401...... NSDictionary *dicHeader = resHttp.allHeaderFields;NSLog(@"headers = %@",dicHeader);}else{NSLog(@"not http");}if(data){NSString *html = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];NSLog(@"%@",html);} }];
//Request NSMutableURLRequest *urlRequest = [NSMutableURLRequest new];[urlRequest setURL:[NSURL URLWithString:@"http://XXX.sinaapp.com/test/test.php"]];[urlRequest setTimeoutInterval:10.0f];[urlRequest setHTTPMethod:@"POST"];[urlRequest setCachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData];NSString *strBody = @"p1=abc&p2=12";[urlRequest setHTTPBody:[strBody dataUsingEncoding:NSUTF8StringEncoding]];NSOperationQueue *queue = [[NSOperationQueue alloc]init];[NSURLConnectionsendAsynchronousRequest:urlRequestqueue:queuecompletionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {//确认是httpif([response isKindOfClass:[NSHTTPURLResponse class]]){NSHTTPURLResponse *resHttp = (NSHTTPURLResponse *)response; NSLog(@"status = %ld",resHttp.statusCode);//200 304 401......NSDictionary *dicHeader = resHttp.allHeaderFields;NSLog(@"headers = %@",dicHeader);}else{NSLog(@"not http");}if(data){NSString *html = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];NSLog(@"%@",html);}}];
(3)Response中有Json数据
//RequestNSMutableURLRequest *urlRequest = [NSMutableURLRequest new];[urlRequest setURL:[NSURL URLWithString:@"http://XXX.sinaapp.com/test/test.php"]];[urlRequest setTimeoutInterval:10.0f];[urlRequest setHTTPMethod:@"POST"];[urlRequest setCachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData];NSString *strBody = @"p1=abc&p2=12";[urlRequest setHTTPBody:[strBody dataUsingEncoding:NSUTF8StringEncoding]];NSOperationQueue *queue = [[NSOperationQueue alloc]init];[NSURLConnectionsendAsynchronousRequest:urlRequestqueue:queuecompletionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {NSError *err2 = nil;id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&err2];if([jsonObject isKindOfClass:[NSDictionary class]]){NSLog(@"NSDictionary");NSDictionary *dic = jsonObject;NSLog(@"dic = %@",dic);}else if([jsonObject isKindOfClass:[NSArray class]]){NSLog(@"NSDictionary");NSDictionary *arr = jsonObject;NSLog(@"arr = %@",arr);}}];
(4)Request中带有Json格式数据
//RequestNSMutableURLRequest *urlRequest = [NSMutableURLRequest new];[urlRequest setURL:[NSURL URLWithString:@"http://XXXX.sinaapp.com/test/test.php"]];[urlRequest setTimeoutInterval:10.0f];[urlRequest setHTTPMethod:@"POST"];[urlRequest setCachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData];[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];//这句没有也没关系NSDictionary *dicRequest = @{@"name":@"leo",@"id":@"456"};NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dicRequest options:NSJSONWritingPrettyPrinted error:nil];[urlRequest setHTTPBody:jsonData];NSOperationQueue *queue = [[NSOperationQueue alloc]init];[NSURLConnectionsendAsynchronousRequest:urlRequestqueue:queuecompletionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {NSError *err2 = nil;id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&err2];if([jsonObject isKindOfClass:[NSDictionary class]]){NSLog(@"NSDictionary");NSDictionary *dic = jsonObject;NSLog(@"dic = %@",dic);}else if([jsonObject isKindOfClass:[NSArray class]]){NSLog(@"NSDictionary");NSDictionary *arr = jsonObject;NSLog(@"arr = %@",arr);}}];
服务器端的处理与返回(将request的值末尾加上_appending,然后返回)
<?phpheader('Access-Control-Allow-Origin:*');$json_string = $GLOBALS['HTTP_RAW_POST_DATA'];$obj = json_decode($json_string);//echo $obj->name;//echo $obj->id;$arr = array("name"=>$obj->name."_appending","id"=>$obj->id."_appending");echo json_encode($arr);
(5)从服务器下载图片(启示就是普通的GET请求,只是将response中的data转为Image而已)
//RequestNSMutableURLRequest *urlRequest = [NSMutableURLRequest new];[urlRequest setURL:[NSURL URLWithString:@"https://res.wx.qq.com/mpres/htmledition/images/pic/case-detail/nfhk_l23b6fe.jpg"]];[urlRequest setTimeoutInterval:10.0f];[urlRequest setHTTPMethod:@"GET"];[urlRequest setCachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData];[NSURLConnectionsendAsynchronousRequest:urlRequestqueue:[NSOperationQueue mainQueue]completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {UIImage *img = [UIImage imageWithData:data];[self.imgView setImage:img];}];
(6)以上所有动作都可以使用代理来做,原理上都是一样的
NSURLConnectionDataDelegate,
NSURLConnectionDelegate,
NSURLConnectionDownloadDelegate
转载于:https://www.cnblogs.com/dongfangchun/p/5285176.html
NSURLConnection的使用相关推荐
- NSURLConnection的简单使用
遵循代理:NSURLConnectionDataDelegate -(void)fetchWebData:(id)sender{ self.isLoading=YES; NSStri ...
- iOS开发之网络编程--使用NSURLConnection实现大文件断点续传下载
前言:iOS开发之网络编程--使用NSURLConnection实现大文件断点续传下载是在前篇iOS开发之网络编程--使用NSURLConnection实现大文件下载的基础上进行 断点续传的设置 ...
- iOS开发网络篇—NSURLConnection基本使用
一.NSURLConnection的常用类 (1)NSURL:请求地址 (2)NSURLRequest:封装一个请求,保存发给服务器的全部数据,包括一个NSURL对象,请求方法.请求头.请求体.... ...
- iOS开发网络篇—NSURLConnection基本使用(一)
一.NSURLConnection的常用类 (1)NSURL:请求地址 (2)NSURLRequest:封装一个请求,保存发给服务器的全部数据,包括一个NSURL对象,请求方法.请求头.请求体.. ...
- iOS网络开发之:NSURLConnection
今天开始打算总结一下在iOS开发中的网络部分 NSURLConnection 这个访问网络的方式最简单,但功能也是最少的因此只有很简单的网络访问才会用到; 使用NSURLConnection访问网络大 ...
- NSURLConnection实现文件上传和AFNetworking实现文件上传
请求的步骤分为4步 1.创建请求 2.设置请求头(告诉服务器这是一个文件上传的请求) 3.设置请求体 4.发送请求 NSURLConnection实现文件上传 // 1.创建请求NSURL *url ...
- 使用NSURLConnection实现大文件断点下载
使用NSURLConnection实现大文件断点下载 由于是实现大文件的断点下载,不是下载一般图片什么的.在设计这个类的时候本身就不会考虑把下载的文件缓存到内存中,而是直接写到文件系统. 要实现断点下 ...
- NSURLConnection 实现webView显示HTTPS页面
NSURLConnection 实现webView显示HTTPS页面我们在浏览器访问https页面的时候的,会弹出: 信任证书我们接下来信任证书以及显示出来遵循协议@interface ViewCon ...
- NSURLConnection和NSRunLoop
主线程中创建一个NSURLConnection并异步运行 [self performSelectorOnMainThread:@selector(start) withObject:nil waitU ...
- NSURLSession和NSURLConnection
iOS9.0之后NSURLConnection被注销,采用NSURLSession,先介绍NSURLSession,然后介绍NSURLConnection 1.NSURLSession: post请求 ...
最新文章
- 这家自动驾驶公司融资2.7亿美元,京东美团齐出手
- VTK:光标形状用法实战
- SVD分解.潜语义分析.PythonCode
- oracle怎么从大字段中取节点,Oracle数据库 获取CLOB字段存储的xml格式字符串指定节点的值...
- QTP自动化测试最佳实践
- 【oracle】sql处理重复数据
- ​LeetCode刷题实战248:中心对称数III
- 移动机器人小众期刊Foundations and Trends in Roboics
- github上成员贡献量_精确统计github贡献者的代码行数
- angular页面间传递参数
- dw设置html背景,Dreamweaver默认浏览器怎么设置
- 数据分析——帆软report
- Lucene DocValues索引文件详解
- Redis学习之缓存数据类型
- Android应用开发编译框架流程与IDE及Gradle概要
- Recommended software
- 我是如何通过系统架构设计师考试的(2017年软考)
- android媲美微信扫码库
- 什么是图灵机及图灵完备(一)
- 【SQL Server】让你的数据来去自如——批处理