1.get请求方式
//1.创建URL,urlStr:网址,str:参数
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",urlStr,str]];
//2.创建网络请求,请求时间最长10秒
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
//3.创建任务
NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if(error) {
//请求失败
}else{
//请求成功,根据后端数据解析
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
}
}];
//开始任务
[dataTaskresume];
2.Post请求方式
//1.创建会话对象
NSURLSession *session = [NSURLSession sharedSession];
//2.根据会话对象创建task
NSURL *url = [NSURL URLWithString:urlstr];
//3.创建可变的请求对象,请求时间最长10秒
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
//4.修改请求方法为POST
request.HTTPMethod=@"POST";
//5.设置请求体:需要传的参数
NSString*prame = str;
request.HTTPBody = [prame dataUsingEncoding:NSUTF8StringEncoding];
//6.根据会话对象创建一个Task(发送请求)
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error){
//8.解析数据
if(error) {
//失败
block(NO,[NSStringstringWithFormat:@"error = %@",error],nil);
}else{
//根据后端数据解析
// NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
}
}];
//7.执行任务
[dataTaskresume];
网友评论