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请求(返回文本)
//Request
NSMutableURLRequest *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:urlRequest
queue:queue
completionHandler:^(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];
[NSURLConnection
sendAsynchronousRequest:urlRequest
queue:queue
completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
//确认是http
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);
}
}];
(3)Response中有Json数据
//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];
[NSURLConnection
sendAsynchronousRequest:urlRequest
queue:queue
completionHandler:^(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格式数据
//Request
NSMutableURLRequest *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]; [NSURLConnection
sendAsynchronousRequest:urlRequest
queue:queue
completionHandler:^(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,然后返回)
<?php
header('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而已)
//Request
NSMutableURLRequest *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]; [NSURLConnection
sendAsynchronousRequest:urlRequest
queue:[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
NSURLConnection的使用的更多相关文章
- NSURLConnection实现文件上传和AFNetworking实现文件上传
请求的步骤分为4步 1.创建请求 2.设置请求头(告诉服务器这是一个文件上传的请求) 3.设置请求体 4.发送请求 NSURLConnection实现文件上传 // 1.创建请求 NSURL *url ...
- iOS网络1——NSURLConnection使用详解
原文在此 一.整体介绍 NSURLConnection是苹果提供的原生网络访问类,但是苹果很快会将其废弃,且由NSURLSession(iOS7以后)来替代.目前使用最广泛的第三方网络框架AFNetw ...
- NSURLConnection学习笔记
虽说现在都用三方库来获取网络数据,再不济也会用苹果官方的NSURLSession,但有些东西还是要先学会才有资格说不好不用,不是么? NSURLConnection发送请求是分为同步和异步两种方式的, ...
- 网络第一节——NSURLConnection
一.NSURLConnection的常用类 (1)NSURL:请求地址 (2)NSURLRequest:封装一个请求,保存发给服务器的全部数据,包括一个NSURL对象,请求方法.请求头.请求体.... ...
- post NSURLConnection请求网络数据
#import "ViewController.h" @interface ViewController () @end @implementation ViewControlle ...
- NSURLConnection 异步加载网络数据
#import "ViewController.h" @interface ViewController () @end @implementation ViewControlle ...
- iOS NSURLConnection POST异步请求封装,支持转码GBK,HTTPS等
.h文件 #import <Foundation/Foundation.h> //成功的回调 typedef void(^successBlock)(id responseObj); // ...
- NSURLConnection使用
*:first-child { margin-top: 0 !important; } body > *:last-child { margin-bottom: 0 !important; } ...
- iOS开发 GET、POST请求方法(NSURLConnection篇)
Web Service使用的主要协议是HTTP协议,即超文本传输协议. HTTP/1.1协议共定义了8种请求方法(OPTIONS.HEAD.GET.POST.PUT.DELETE.TRACE.CONN ...
随机推荐
- Sharepoint学习笔记—习题系列--70-576习题解析 -(Q141-Q143)
Question 141 You are planning an upgrade to a SharePoint 2010 application. You have the following r ...
- mvp+retrofit+rxjava
引用 "retrofit" : "com.squareup.retrofit2:retrofit:2.0.1", "retrofit-adapter& ...
- Android编码规范01
目标: 掌握Java & Android命名规范 在研究Android源代码的基础上改进命名规范 考核内容 说出四种常用的命名法 比较java和C#的命名规范的不同点 总结: 读不同程序员写的 ...
- Masonry使用注意事项
1 理解自身内容尺寸约束与抗压抗拉 自身内容尺寸约束:一般来说,要确定一个视图的精确位置,至少需要4个布局约束(以确定水平位置x.垂直位置y.宽度w和高度h).但是,某些用来展现内容的用户控件,例如文 ...
- SQL Challenge ——快速找到1-100之间缺失的数
有个经典的题目:1-100之间的数字(不重复)存放在表里,共95行一列,但是里面缺了5个数字,怎么用SQL最快找出那五个数字. 我们先来看看Oracle数据库如何实现,如下所示,我们先准备测试环境和数 ...
- [解决]Mercurial HTTP Error 500: Access is denied on 00changelog.i
总之,用户对仓库目录要有写权限 00changelog, access is denied, hg, http error 500, mercurial, permissions, push Merc ...
- c#中对txt文件的读取与写入,针对二维数组
class Program { ; ; static string[,] str = new string[ROW, COL]; static void Main(string[] args) { R ...
- 一个"如何使用示波器安全测试接市电电路板"的问题
最近犯了一个错误测试操作: 测试场景:直接从市电插座取电接入3W非隔离开关电源电路板,使用示波器测试输出电压,此时示波器通过另外一个插座直接从市电取电 测试后果:在将示波器接到输出负极的一瞬间,漏电保 ...
- GLine游戏(Win32GUI实现,CodeBlocks+GCC编译)
游戏规则: 在10X10的棋盘上有五种颜色的棋子. 点击一个棋子,再点击一个空格子,如果两者之间有一条路径的话,棋子会移动到空格子内. 每移动一次,棋盘上会增加三个棋子,其位置和颜色都是随机的. 当横 ...
- Freemarker与Servlet
1.导入jar包(freemarker.jar) 2.web.xml配置一个普通servlet <servlet> <servlet-name>hello</servle ...