GET请求方式一
//1 获得NSURLSession对象(默认对象)---->默认开启异步
NSURLSession *session = [NSURLSession sharedSession];
//2 获取url
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=4324"];
//3 创建NSURLRequest请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//4 创建任务
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//data---->json
id json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(@"获取的响应体数据:%@",json);
NSString *dataStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"获取的响应体数据:%@",dataStr);
NSLog(@"获取的URL、状态编码和响应头数据%@",response);
NSHTTPURLResponse *urlResponse = (NSHTTPURLResponse *)response;
NSInteger statuCode = urlResponse.statusCode;
NSLog(@"状态编码:%ld",statuCode);
NSLog(@"错误的信息:%@",error);
NSLog(@"------%@",[NSThread currentThread]);
}];
//5 恢复任务(恢复任务后,再回调执行block里的代码)
[dataTask resume];
GET请求方式二
NSURLSession *session = [NSURLSession sharedSession];
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=4324"];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSString *dataStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"获取的响应体数据:%@",dataStr);
}];
[dataTask resume];
POST请求方式
//1 获得NSURLSession对象
NSURLSession *session = [NSURLSession sharedSession];
//2 创建请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/login"]];
//2.1请求方式:默认是GET
request.HTTPMethod = @"POST";
//2.2请求体
request.HTTPBody = [@"username=123&pwd=123"dataUsingEncoding:NSUTF8StringEncoding];
//2.3缓存策略
request.cachePolicy = NSURLRequestUseProtocolCachePolicy;
//2.4设置超时时间
request.timeoutInterval = 5;
//2.5设置请求头
[request setValue:@"zh-cn" forHTTPHeaderField:@"Accept-Language"];
//3 创建任务
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//data---->json
id json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(@"获取的响应体数据:%@",json);
NSString *dataStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"获取的响应体数据:%@",dataStr);
NSHTTPURLResponse *urlResponse = (NSHTTPURLResponse *)response;
NSInteger statuCode = urlResponse.statusCode;
NSLog(@"状态编码:%ld",statuCode);
NSDictionary *headResponse = urlResponse.allHeaderFields;
NSLog(@"获取的响应头数据%@",headResponse);
NSLog(@"获取的URL、状态编码和响应头数据%@",response);
//取得响应头中的信息项
NSString *contentType = [urlResponse.allHeaderFields objectForKey:@"Content-Type"];
NSLog(@"信息项:%@",contentType);
NSLog(@"错误的信息:%@",error);
NSLog(@"------%@",[NSThread currentThread]);
}];
//恢复任务
[dataTask resume];
代理方式请求(这里用到了NSURLSessionConfiguration网络会话配置)
@interface ViewController ()<NSURLSessionDataDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
//设置缓存策略
config.requestCachePolicy = NSURLRequestUseProtocolCachePolicy;
//设置网络服务类型
config.networkServiceType = NSURLNetworkServiceTypeDefault;
//设置超时
config.timeoutIntervalForRequest = 10;
//设置请求头
config.HTTPAdditionalHeaders = @{@"Accept-Language":@"zh-cn"};
//设置后台请求,会把wifi、电量的可用性考虑在内
config.discretionary = YES;
//设置是否允许使用蜂窝数据
config.allowsCellularAccess = YES;
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=4324"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[[NSOperationQueue alloc]init] ];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url];
[dataTask resume];
}
#pragma mark - <NSURLSessionDataDelegate>
/**
* 1.接收到服务器的响应
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
NSLog(@"%s", __func__);
// 允许处理服务器的响应,才会继续接收服务器返回的数据
completionHandler(NSURLSessionResponseAllow);
}
/**
* 2.接收到服务器的数据(可能会被调用多次)
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
NSString *dataStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"dataStr:%@",dataStr);
NSLog(@"%s", __func__);
}
/**
* 3.请求成功或者失败(如果失败,error有值)
*/
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
NSLog(@"%s", __func__);
}
网络请求简单下载
// 获得NSURLSession对象
NSURLSession *session = [NSURLSession sharedSession];
// 获得下载任务
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"] completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
// 文件将来存放的真实路径--->在沙盒cache里面存储文件
NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
// 剪切location的临时文件到真实路径
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
}];
// 启动任务
[task resume];