在iOS中,常见的发送HTTP的请求有
苹果自带的
- NSURLConnection
- NSURLSession
- CFNetworking
第三方框架
- AFNetworking
- ASIHttpRequest
就目前来看,比较火的是NSURLSession和AFNetworking,但是NSURLConnection目前也会在使用。学了这几种之后,想做一个方法的简单整理
本编是关于NSURLConnection的使用方法的简单整理
NSURLConnection
常用类
- NSURL:请求地址
- NSURLRequest:一个NSURLRequest对象就代表一个请求,它包含的信息有
- 一个URL对象
- 请求方法、请求头、请求体
- 请求超时
- … …
- NSMutableURLRequest:NSURLRequest的子类
- NSURLConnection
- 负责发送请求,建立客户端和服务器的连接
- 发送数据给服务器,并收集来自服务器的响应数据
NSURLConnection的使用步骤
使用NSURLConnection发送请求的步骤很简单
- 创建一个NSURL对象,设置请求路径
- 传入NSURL创建一个NSURLRequest对象,设置请求头和请求体
- 使用NSURLConnection发送请求
NSURLConnection发送请求
常见方法有如下几种
同步请求
NSURLConnection sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error;
异步请求
NSURLConnection sendAsynchronousRequest:(NSURLRequest *)request queue:(NSOperationQueue *)queue completionHandler:(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError);
代理方法
- (nullable instancetype)initWithRequest:(NSURLRequest *)request delegate:(nullable id)delegate startImmediately:(BOOL)startImmediately ;
- (nullable instancetype)initWithRequest:(NSURLRequest *)request delegate:(nullable id)delegate;
+ (nullable NSURLConnection*)connectionWithRequest:(NSURLRequest *)request delegate:(nullable id)delegate;
这三个方法任意一个均可调用,但是用法有说不同,文档中写的很清楚,在这里做个小的归纳总结,方便以后自己对照使用。
在startImmediately=NO的情况下,需要调用start方法开始发送请求
-(void)start;
成为NSURLConnection的代理,最好遵守NSURLConnectionDataDelegate的协议,常用的代理方法有
/**
* 接收到服务器的响应
*/
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"didReceiveResponse");
}
/**
* 接收到服务器的数据(如果数据量比较大,这个方法会被调用多次)
*/
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"didReceiveData -- %zd", data.length);
}
/**
* 服务器的数据成功接收完毕
*/
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"connectionDidFinishLoading");
}
/**
* 请求失败(比如请求超时)
*/
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"didFailWithError -- %@", error);
}
下面给出上面的三种方法的具体代码供参考理解
同步跟异步方法的区别,知道多线程都了解啦,同步是在主线程做事,是阻塞式的。异步是另外开一条线程,不会阻塞主线程的操作执行
以下代码实现代码为GET方法
同步方法具体代码实现
// 0.请求路径
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=345"];
// 1.创建请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2.发送请求
// sendSynchronousRequest阻塞式的方法,等待服务器返回数据
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
// 3.解析服务器返回的数据(解析成字符串)
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@ ", string);
异步方法具体代码实现
// 0.请求路径
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it"];
// 1.创建请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2.发送请求
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// 请求完毕会来到这个block
// 3.解析服务器返回的数据(解析成字符串)
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", string);
}];
代理方法具体代码实现
- (void)delegateAysnc
{
// 0.请求路径
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it"];
// 1.创建请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2.创建连接对象
// [[NSURLConnection alloc] initWithRequest:request delegate:self];
// NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
// [conn start];
[NSURLConnection connectionWithRequest:request delegate:self];
//然后写你自己需要的代理方法即可,上面有写一些常用的,没有写到的可以自己看文档
}
以上均为GET方法,
下面花个小篇幅写下关于POST方法的
先PO代码,之后再解释。
// 1.请求路径
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"];
// 2.创建请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 更改请求方法
request.HTTPMethod = @"POST";
// 设置请求体
request.HTTPBody = [@"username=520it&pwd=520it" dataUsingEncoding:NSUTF8StringEncoding];
// 设置超时(5秒后超时)
request.timeoutInterval = 5;
// 设置请求头,看个人需求
// [request setValue:@"iOS 9.0" forHTTPHeaderField:@"User-Agent"];
// 3.发送请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError) { // 比如请求超时
NSLog(@"----请求失败");
} else {
NSLog(@"------%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}
}];
由于GET方法和POST的方法区别我之前的文章也有写到,GET方法的参数是直接写在URL后面的,当POST方法不同,参数是全部放在请求体中,所以需要设置请求体。
并且NSURLRequest的默认方式 是GET请求,这时候就需要你去修改,需要用到它的可变之类,NSMutableURLRequest改变他的请求类型为POST。
关于NSMutableURLRequest具体方法如下
/*
*设置请求超时等待时间(超过这个时间就算超时,请求失败)
*/
-(void)setTimeoutInterval:(NSTimeInterval)seconds;
/*
*设置请求方法(比如GET和POST)
*/
-(void)setHTTPMethod:(NSString*)method;
/*
*设置请求体方法
*/
-(void)setHTTPBody:(NSData*)data;
/*
*设置请求头方法
*/
-(void)setValue:(NSString*)value forHTTPHeaderField:(NSString*)field;
差不多就这些,之后我会写一篇转码的文档,有兴趣可以看一看。
在这里说明,我是MJ老师的死忠粉,所以都是看他的视频和代码来学习的。
以上,如有建议和错误欢迎指出,我会及时修正。