The NSURLConnection class provides convenience class methods to load URL requests both asynchronously using a callback block and synchronously.(NSURLConnection提供采用回调方式的异步请求和同步请求)
During a request, the connection maintains a strong reference to its delegate. It releases that strong reference when the connection finishes loading, fails, or is canceled.(在请求期间,NSURLConnection对它的委托保持强引用,当结束请求或者请求失败、被取消时才会释放对委托的引用)
一、NSURLConnection的常用类
(1)NSURL:请求地址
(2)NSURLRequest:封装一个请求,保存发给服务器的全部数据,包括一个NSURL对象,请求方法、请求头、请求体….
(3)NSMutableURLRequest:NSURLRequest的子类
(4)NSURLConnection:负责发送请求,建立客户端和服务器的连接。发送NSURLRequest的数据给服务器,并收集来自服务器的响应数据
二、NSURLConnection的使用
1.步骤
(1)设置请求路径.创建一个NSURL对象,设置请求路径(设置请求路径)
(2)创建请求对象.传入NSURL创建一个NSURLRequest对象,设置请求头和请求体(创建请求对象)
(3)发送请求.使用NSURLConnection发送NSURLRequest(发送请求)
2.同步请求与异步请求
(1)同步请求.服务器无返回数据会阻塞当前线程,有返回值1
2
3
4
5
6
7
8//1.设置请求路径
NSString *urlStr=[NSString stringWithFormat:@"http://192.168.0.101:8080/GWServer/login?username=%@&pwd=%@",self.username.text,self.pwd.text];
NSURL *url=[NSURL URLWithString:urlStr];
//2.创建请求对象
NSURLRequest *request=[NSURLRequest requestWithURL:url];
//3.发送同步请求,在主线程执行,iOS9.0已弃用 sendSynchronousRequest
NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSLog(@"--%d--",data.length);
(2)异步请求.无返回值,两种方式:使用block回调或者使用代理
使用block回调
1 | //创建一个队列(默认添加到该队列中的任务异步执行) |
代理
- NSURLConnectionDelegate调用代理方法
connection:didFailWithError:
- NSURLConnectionDataDelegate调用代理方法
connection:didReceiveResponse:
,connection:didReceiveData:
,connectionDidFinishLoading:
- NSURLConnectionDownloadDelegate
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36//设置请求路径
NSString *urlStr=[NSString stringWithFormat:@"http://192.168.1.101:8080/GWServer/login?username=%@&pwd=%@",self.username.text,self.pwd.text];
NSURL *url=[NSURL URLWithString:urlStr];
//创建请求对象
// NSURLRequest *request=[NSURLRequest requestWithURL:url];//默认就是GET请求
//设置请求超时
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
request.timeoutInterval=5.0;
//发送请求
NSURLConnection *conn=[NSURLConnection connectionWithRequest:request delegate:self];
#pragma mark- NSURLConnectionDataDelegate代理方法
//接收到服务器的响应
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//初始化数据
self.responseData=[NSMutableData data];
}
//接收到服务器的数据
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
//拼接数据
[self.responseData appendData:data];
NSLog(@"%d---%@--",self.responseData.length,[NSThread currentThread]);
}
//服务器的数据加载完毕
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//处理服务器返回的所有数据
NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:nil];
NSLog(@"%d---%@--",self.responseData.length,[NSThread currentThread]);
}
//请求失败
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"请求错误");
}