在
iOS
中,常见的发送
HTTP
请求(
GET
和
POST
)的解决方案有
苹果原生(自带)
NSURLConnection
:用法简单,最古老最直接的一种方案
NSURLSession
:
iOS
7
新出的技术,功能比
NSURLConnection
更加强大
CFNetwork
:
NSURL
*的底层,纯
C
语言
第三方框架
ASIHttpRequest
:外号“
HTTP
终结者”,功能极其强大,可惜早已停止更新
AFNetworking
:简单易用,提供了基本够用的常用功能
NSURLConnection常用类
主要为三个对象:
NSURL
请求的地址
NSURLRequest(NSMutableURLRequest:NSURLRequest的子类)
封装一个请求,保存发给服务器的全部数据
NSURLConnection
负责发送请求
,
建立客户端和服务器的连接
发送
NSURLRequest
的数据给服务器,并收集来自服务器的响应数据
1.
创建一个
NSURL
对象,设置请求路径
2.
传入
NSURL
创建一个
NSURLRequest
对象,设置请求头和请求体
(GET方法不需要设置请求体,POST方法需要设置请求体)
3.
使用
NSURLConnection
发送
NSURLRequest
( 可使用3中方式发送,同步方法,异步方法,代理方法(异步方式))
代码示例:
1.
创建一个
NSURL
对象,设置请求路径
2.
传入
NSURL
创建一个
NSURLRequest
对象,设置请求头和请求体
(1. GET方式)
// 1.1.1 设置请求路径
NSString *urlStr = [NSString stringWithFormat:@"http://192.168.1.200:8080/MJServer/login?username=%@&pwd=%@", username, pwd];
// 1.1.2转码 (URL里面不能包含中文,所以需要转码)
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// 1.1.3 URL里面不能包含中文
NSURL *url = [NSURL URLWithString:urlStr];
// 2.1.2.根据url创建请求对象(NSURLRequest 不能修改request的值,所以使用可变请求)
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; // 默认就是GET请求
request.timeoutInterval = 5; // 设置请求超时
(2. POST方式)
// POST请求:请求体
// 1.2.1.设置请求路径
NSURL *url = [NSURL URLWithString:@"http://192.168.1.200:8080/MJServer/login"];
// 2.2.1.创建请求对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; // 默认就是GET请求
request.timeoutInterval = 5; // 设置请求超时
request.HTTPMethod = @"POST"; // 设置为POST请求
// 2.2.2通过请求头告诉服务器客户端的类型
[request setValue:@"ios" forHTTPHeaderField:@"User-Agent"];
// 2.2.3设置请求体
NSString *param = [NSString stringWithFormat:@"username=%@&pwd=%@", username, pwd];
request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];
GET和POST对比
GET
和
POST
的主要区别表现在数据传递上
GET
在请求
URL
后面以
?
的形式跟上发给服务器的参数,多个参数之间用
&
隔开,比如
http://ww.test.com/login?username=123&pwd=234&type=JSON
由于浏览器和服务器对
URL
长度有限制,因此在
URL
后面附带的参数是有限制的,通常不能超过
1KB
POST
发给服务器的参数统统放在
请求体
中
理论上,
POST
传递的数据量没有限制(具体还得看服务器的处理能力)
(接上面的代码)
3.1.使用NSURLConnection发送NSURLRequest (同步方法)
// 3.1.1 使用同步方式发送请求(此方法是在主线程中发送,UI会卡,基本不使用)
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// 3.1.2把data转换成字符串答应
NSString *dataStr= [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",dataStr);
3.2.使用NSURLConnection发送NSURLRequest (异步方法)
//3.2.1 使用异步方式发送请求(一般会根据获得的data数据来刷新UI空间,所以队列使用 mainQueue)
NSOperationQueue *queue = [NSOperationQueue mainQueue];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { // 当请求结束的时候调用 (拿到了服务器的数据, 请求失败)
//3.2.2 把data转换成字符串答应
NSString *dataStr= [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",dataStr);
/**
解析data :
{"error":"用户名不存在"}
{"error":"密码不正确"}
{"success":"登录成功"}
*/
/**
if (data) { // 请求成功
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSString *error = dict[@"error"];
if (error) { // 登录失败
[MBProgressHUD showError:error];
} else { // 登录成功
NSString *success = dict[@"success"];
[MBProgressHUD showSuccess:success];
}
} else { // 请求失败
[MBProgressHUD showError:@"网络繁忙, 请稍后再试"];
}
*/
}];
3.3.使用NSURLConnection发送NSURLRequest (代理方法,异步方式)
// 3.3.1 设置request 与 代理
NSURLConnection *conn4 = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
// 3.3.2 发送请求
[conn4 start];
需要实现代理
<NSURLConnectionDataDelegate>
一下是代理方法
#pragma mark - NSURLConnectionDataDelegate 代理方法
/**
* 请求错误(失败)的时候调用(请求超时\断网\没有网, 一般指客户端错误)
*/
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"connection:didFailWithError:");
}
/**
* 当接受到服务器的响应(连通了服务器)就会调用
*/
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"connection:didReceiveResponse:");
// 初始化数据
/**
* 用来存放服务器返回的所有数据
* @property (nonatomic, strong) NSMutableData *responseData;
*/
self.responseData = [NSMutableData data];
}
/**
* 当接受到服务器的数据就会调用(可能会被调用多次, 每次调用只会传递部分数据)
*/
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"connection:didReceiveData:");
// 拼接(收集)数据
[self.responseData appendData:data];
}
/**
* 当服务器的数据接受完毕后就会调用
*/
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"connectionDidFinishLoading:");
// 解析服务器返回的数据
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:nil];
NSString *error = dict[@"error"];
if (error) { // 登录失败
NSLog(@"登录失败");
} else { // 登录成功
NSString *success = dict[@"success"];
NSLog(@"登录成功:%@",success);
}
}