HTTP是一个客户端终端(用户)和服务器端(网站)请求和应答的标准(TCP)。通过使用Web浏览器、网络爬虫或者其它的工具,客户端发起一个HTTP请求到服务器上指定端口(默认端口为80)1。
HTTP/1.1协议中共定义了四中基本方法来以不同方式操作指定的资源: GET, POST, PUT, DELETE
.
iOS SDK中提供了同步(Synchronize)和异步(Asynchronous)请求. 其中:
- 同步请求, 向网络发送同步请求数据, 一旦请求发送, 程序停止用户交互, 直到服务器返回数据或出现错误.
- 异步请求, 会建立一个新的线程来操作数据请求而不影响用户交互.
- GET方式将表单请求中的参数拼接在地址中进行传递, 参数数量和长度不能超过255字节
- POST方式地址栏中不会有表单请求等参数, 参数数量和长度没有限制
以下通过登录接口介绍其不同.
static NSString *const kGetUrl = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
static NSString *const kPostUrl = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
static NSString *const kPostBody = @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
一. GET方法
1. get 方式进行同步请求
- (void)getSyncRequestEvent {
// 网络请求
// 1.生成URL
NSURL *url = [NSURL urlWithString:kGetUrl];
// 2.创建请求对象
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
// 3.发送请求
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil
error:ni];
}
由于一些苛刻的限制条件, 苹果官方不推荐使用该方法2.
2. get 代理方式进行异步请求
get 代理方式异步请求需要遵守协议:NSURLConnectionDataDelegate
:
@interface RootViewController ()<NSURLConnectionDataDelegate>
/** 最终结果数组 */
@property (nonatomic, strong) NSMutableArray *data;
/** 缓冲数据 */
@property (nonatomic, strong) NSMutableData *tempData;
@end
- (void)getDelegateAsyncEvent {
// 1.创建URL对象
NSURL *url = [NSURL URLWithString:kGetUrl];
// 2.创建URLRequest对象
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
// 3.注意:同步和异步的不同()
[NSURLConnection connectionWithRequest:request delegate:self];
}
该协议中有3个可用的可选方法(@optional
):
// 当收到服务器响应的时候
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// 初始化结果数组
self.data = [NSMutableArray array];
// 初始化缓冲水桶
self.tempData = [NSMutableData data];
}
// 接收数据时
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.tempData appendData:data];
}
// 当所有数据接收完毕
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
// 对水桶中所有数据进行解析
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:self.tempData options:NSJSONReadingAllowFragments error:nil];
// parse...
}
3.使用block方式实现get异步
- (void)getBlockAsyncAction {
// 创建URL
NSURL *url = [NSURL URLWithString:BCGETURL];
// 创建请求对象
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
// 发送异步请求
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse * _Nullable response,
NSData * _Nullable data,
NSError * _Nullable connectionError) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
// parse...
}];
}
二. POST方法
1.post 方式进行同步请求
- (void)postSyncRequestEvent {
// 1.创建URL对象
NSURL *url = [NSURL urlWithString:kPostUrl];
// 2.创建请求对象
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
//注意 POST 和 GET 的不同
// 2.1设置HTTPMethod
[request setHTTPMethod:@"POST"];
// 2.2设置HTTPBody
NSData *bodyData = [kPostBody dataUsingEncoding:NSUTF8StringEncoding];
NSData *dataRequest = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
}
2. post代理异步
post代理异步请求同get代理类似使用协议NSURLConnectionDataDelegate
中的方法, 区别在于设置HTTPBody
和HTTPMethod
.
三. NSURLSession中的方法
苹果官方在iOS7或OS X v10.9以后开始使用了NSURLSessionAPI34
1.post方法
- (void)postRequestEvent {
// 1.创建url对象
NSURL *url = [NSURL URLWithString:kPostUrl];
// 2.创建请求对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 3.设置post属性
[request setHTTPMethod:@"POST"];
NSData *dataBody = [kPostBody dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:dataBody];
// 注意!!!!!新方法的不同
// 4.1创建会话 拿到与服务器的会话
NSURLSession *session = [NSURLSession sharedSession];
// 4.2 创建数据请求任务
NSURLSessionDataTask *task =
[session dataTaskWithRequest:request
completionHandler:^(NSData * _Nullable data,
NSURLResponse * _Nullable response,
NSError * _Nullable error) {
// parse...
}];
// 4.3 启动任务
[task resume];
}
2. get方法
- (void)getRequestEvent {
// 1.创建url
NSURL *url = [NSURL URLWithString:kGetUrl];
// 2.创建请求对象
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
// 3 创建会话
NSURLSession *session = [NSURLSession sharedSession];
// 4.创建任务
NSURLSessionDataTask *task =
[session dataTaskWithRequest:request
completionHandler:^(NSData * _Nullable data,
NSURLResponse * _Nullable response,
NSError * _Nullable error) {
// parse...
}];
// 5.开始任务
[task resume];
}