- 1.同步请求,一旦发送请求,程序禁止用户交互,直到服务器返回数据完成,才能进行下一步操作
- 2.异步请求不会阻塞主线程,而回建立一个新的线程来操作,用户发出请求以后,可以继续对UI操作,程序可以继续运行
-
- 3.GET请求,将参数直接写在访问路径上。操作简单,但是容易被外界看到,安全性不高。
- 4.POST请求,将参数放到body里面,POST操作相对复杂,需要将参数和地址分开,相对更加安全.
GET请求
NSString *urlString = KgetUrl;
NSURL *url = [NSURL URLWithString:urlString];
//创建请求体
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//创建一个session对象
NSURLSession *session = [NSURLSession sharedSession];
//创建请求任务
NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSString *result = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"GTE:%@",result);
}];
//注意不能忘了这一步
[task resume];
POST请求
NSString *urlString = KpostUrl;
NSURL *url = [NSURL URLWithString:urlString];
//创建请求体,注意是 NSMutableURLRequest
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//设置为POST请求
[request setHTTPMethod:@"POST"];
NSString *postString = KparameterUrl;
NSData *data = [postString dataUsingEncoding:NSUTF8StringEncoding];
//添加参数
[request setHTTPBody:data];
//创建session对象
NSURLSession *session = [NSURLSession sharedSession];
//创建一个请求任务
NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSString *result = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"POST%@",result);
}];
[task resume];
代理
- (IBAction)delegateAction:(UIButton *)sender {
//遵循代理 <NSURLSessionDataDelegate>
//
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
//新建任务
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:KgetUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
//创建请求
NSURLSessionDataTask *task = [session dataTaskWithRequest:request];
[task resume];
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler{
//当网络基于HTTP协议时,response是NSHTTPURLResponse类型的
// NSHTTPURLResponse *URLResponse = (NSHTTPURLResponse *)response;
// long long length = URLResponse.expectedContentLength;
// NSLog(@"%ld",URLResponse.statusCode);
// NSLog(@"%lld",length);
//允许服务器回传数据
completionHandler(NSURLSessionResponseAllow);
}
//接受服务器传回来的数据,可能执行多次
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{
NSString *string=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
if (string) {
[self.astring appendString:string];
}
NSLog(@"%@",self.astring);
}
//接受或者失败时调用
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
NSLog(@"%@******",error);
}