一、异步
1、GET请求(BLOCK)
//初始化一个session
NSURLSession *session = [NSURLSession sharedSession];
//通过地址得到一个url
NSString *urlStr = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
NSURL *url = [NSURL URLWithString:urlStr];
//通过单例的session得到一个sessionTask,且通过URL初始化task 在block内部可以直接对返回的数据进行处理
NSURLSessionTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//请求之后会调用这个block
NSString *resultStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"resultStr->%@",resultStr);
}];
//启动人物,让task开始之前执行
[task resume];
2、POST请求(BLOCK)
NSString *urlString = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
NSURL *url = [NSURL URLWithString:urlString];
//初始化request 并配置httpBody httpMethod
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:30];
request.HTTPBody = [@"date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213" dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPMethod = @"POST";
//配置session 并让task开始执行
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSString *resultStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"resultStr->%@",resultStr);
}];
[task resume];
3、Delegate请求
#pragma mark - NSURLSessionDataDelegate代理方法
//服务器开始响应,客户端将要接收数据
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response
completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler
{
//允许服务器开始响应
completionHandler(NSURLSessionResponseAllow);
// NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
self.mulData = [NSMutableData data];
}
//接收数据(会调用多次)
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
//处理每次接受到得数据
//将每次接收到的data片段,拼接到_mulData
[_mulData appendData:data];
}
//数据接收完成,网络请求成功
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
NSLog(@"result->%@",[[NSString alloc]initWithData:_mulData encoding:NSUTF8StringEncoding]);
}
网友评论