数据请求 (一) HTTP 协议采用请求/相应模型. 客户端想服务器发送一个请求报文, 服务器以一个状态作为响应. 服务器端找不到客户端. (二) . HTTP协议的常见请求方式 (1).GET (2).POST 相同点: 都能给服务器传输数据 (三) . IOS 实现网络编程
post 请求方式,1,需要设置请求方式(setHttpMethod:方法) 2.要给request 设置上传的Data . (setHttpBoby:方法); 异步连接:两种方式: 1.异步代理 2.异步Block 上代码 拖到ViewController.m info.plist 中 ViewController.m #import "ViewController.h" @interface ViewController ()<NSURLConnectionDataDelegate> // 保存网络请求的data @property (nonatomic, strong) NSMutableData *resultData; @property (nonatomic, strong) NSDictionary *dictionary; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; } (一) // get同步 // 开发中不推荐使用同步网络请求. - (IBAction)getT:(id)sender { //地址不能存在空格 NSString *urlString = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"; //统一资源定位符 (URL) NSURL *url = [NSURL URLWithString:urlString]; // 第一个参数: 统一资源定位符 // 二参 : 缓存策略 // 三参 : 超时时间 /* [NSURLRequest requestWithURL:<#(nonnull NSURL *)#> cachePolicy:<#(NSURLRequestCachePolicy)#> timeoutInterval:<#(NSTimeInterval)#>] (NSURLRequestCachePolicy)//按command出来下面7个. NSURLRequestUseProtocolCachePolicy : 基础缓存策略 NSURLRequestReloadIgnoringLocalCacheData : 忽略本地缓存 NSURLRequestReloadIgnoringLocalAndRemoteCacheData : 忽略本地缓存, 无论本地是否有缓存,都从网络下载. NSURLRequestReloadIgnoringCacheData = NSURLRequestReloadIgnoringLocalCacheData : 如果本地缓存有效, 则不下载 ,无效则去下载. NSURLRequestReturnCacheDataElseLoad : 优先的使用本地缓存, 如果本地没有缓存, 则去下载. NSURLRequestReturnCacheDataDontLoad :从不下载, 只使用本地缓存, 如果没有则请求失败, 多用于离线环境 NSURLRequestReloadRevalidatingCacheData : 验证本地数据和网络数据是否相同, 如果相同 , 则去下载 ,如果不同, 则使用. 第 2,6,7,多用.7比较好 */ NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0f]; //NSURLConnection 在IOS 9.0 之后不推荐使用 // 一参 : NSURLRequest 类型的对象 // 二参 : 存储一些网络请求信息, 一般为 Nil // 三参 : 错误信息 NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil] ; NSLog(@"data === %@", data); self.dictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; } //post同步 - (IBAction)postT:(id)sender { NSString *urlString = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"; //统一资源定位符 (URL) NSURL *url = [NSURL URLWithString:urlString]; NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url]; // 创建一个字符串 NSString *dataString = @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"; // 把这个字符串转化成NSData类型的对象. NSData *postData = [dataString dataUsingEncoding:NSUTF8StringEncoding]; //设置请求方式要用大写.如POST //GET请求可以不设置. 但是POST必须设置,因为默认为GET [urlRequest setHTTPMethod:@"POST"]; // 把需要上传的data放进request里面. [urlRequest setHTTPBody:postData]; //获取网络数据 NSData *dataa = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil]; //解析网络数据 NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:dataa options:NSJSONReadingAllowFragments error:nil]; NSLog(@"dic ==== %@", dic); } //get异步 block //get异步 - (IBAction)getY:(id)sender { //创建url地址 NSString *urlString = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"; NSURL *url = [NSURL URLWithString:urlString]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; //调用带有block回调的方法 , 执行网络请求 //一参 : NSURLRequest //二参 : block块里面的代码在哪个线程去执行 (固定的) 这行与代理不同 [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { // response 携带的是接口的一些信息. // data 请求下来的数据, 需要使用的. // connectionError 错误信息. if (connectionError == nil) { NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; NSLog(@"dic === %@", dic); //这里应该刷新UI了 // 1.给数据源数组赋值 // 2.赋值结束之后, 刷新 UI ([self.tableView reloadData]); // 3.系统的主线程只做 更新UI. } }]; } //post异步 block - (IBAction)postY:(id)sender { NSString *urlStirng = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"; NSURL *url = [NSURL URLWithString:urlStirng]; NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url]; //创建一个字符串 NSString *dataString = @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"; //转化成NSData NSData *postData = [dataString dataUsingEncoding:NSUTF8StringEncoding]; //设置请求方式要用大写.如POST //GET请求可以不设置. 但是POST必须设置 [urlRequest setHTTPMethod:@"POST"]; // 把需要上传的data放进request里面. [urlRequest setHTTPBody:postData]; //获取网络数据 //调用带有block回调的方法 , 执行网络请求 //一参 : NSURLRequest //二参 : block块里面的代码在哪个线程去执行 (固定的) 这行与代理不同 [NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { // response 携带的是接口的一些信息. // data 请求下来的数据, 需要使用的. // connectionError 错误信息. if (connectionError == nil) { NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; NSLog(@"dic === %@", dic); //这里应该刷新UI了 // 1.给数据源数组赋值 // 2.赋值结束之后, 刷新 UI ([self.tableView reloadData]); // 3.系统的主线程只做 更新UI. } }]; } //get异步 代理 - (IBAction)getY:(id)sender { //创建url地址 NSString *urlString = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"; NSURL *url = [NSURL URLWithString:urlString]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; //代理模式 //代理的异步网络请求 (GET) //一参 : NSURLRequest //二参 : 代理人. 这行与block不同 [NSURLConnection connectionWithRequest:request delegate:self]; } ////////下面与POST的一样 //服务器开始响应 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {//初始化保存结果的data self.resultData = [NSMutableData data]; } //接受到数据 //这个方法会重复的执行, 所以可能拿到一段一段的数据, 这就需要我们把这些数据拼接起来. - (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { // 为了防止 拿到的数据不全, 所以把拿到的数据拼接到保存结果的data中. [self.resultData appendData:data]; } //结束响应 - (void) connectionDidFinishLoading:(NSURLConnection *)connection { NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.resultData options:NSJSONReadingAllowFragments error:nil]; NSLog(@"%@", dic); //更新数据源数组 //刷新UI } //post异步 代理 - (IBAction)postY:(id)sender { NSString *urlStirng = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"; NSURL *url = [NSURL URLWithString:urlStirng]; NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url]; //创建一个字符串 NSString *dataString = @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"; //转化成NSData NSData *postData = [dataString dataUsingEncoding:NSUTF8StringEncoding]; //设置请求方式要用大写.如POST //GET请求可以不设置. 但是POST必须设置 [urlRequest setHTTPMethod:@"POST"]; // 把需要上传的data放进request里面. [urlRequest setHTTPBody:postData]; //代理模式 //代理的异步网络请求 (GET) //一参 : NSURLRequest //二参 : 代理人. 这行与block不同 [NSURLConnection connectionWithRequest:urlRequest delegate:self]; ////////下面与GET的一样 #pragma mark --- NSURLConnectionDataDelegate //服务器开始响应 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {//初始化保存结果的data self.resultData = [NSMutableData data]; } //接受到数据 //这个方法会重复的执行, 所以可能拿到一段一段的数据, 这就需要我们把这些数据拼接起来. - (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { // 为了防止 拿到的数据不全, 所以把拿到的数据拼接到保存结果的data中. [self.resultData appendData:data]; } //结束响应 - (void) connectionDidFinishLoading:(NSURLConnection *)connection { NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.resultData options:NSJSONReadingAllowFragments error:nil]; NSLog(@"%@", dic); //更新数据源数组 //刷新UI }
NSURLSession : 没用同步,异步之分 ViewController.m #import "ViewController.h" // NSURLSessionDataDelegate NSURLSession获取网络数据的代理协议 @interface ViewController ()<NSURLSessionDataDelegate> // 保存结果的data @property (nonatomic, strong) NSMutableData *resultData; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; } POST代理 - (IBAction)post:(id)sender { NSString *urlString = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"; NSURL *url1 = [NSURL URLWithString:urlString]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url1]; NSString *postString = @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"; NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding]; [request setHTTPMethod:@"POST"]; [request setHTTPBody:postData]; NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]]; // NSURLSessionTask 的子类 NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request];//没有代理的回调 [dataTask resume]; } //服务器开始响应 - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler { //NSURLSession的代理协议里面, 必须设置允许继续请求, 才会继续响应服务器. 获取到数据.吗; completionHandler(NSURLSessionResponseAllow); self.resultData = [NSMutableData data]; } //接收到数据 - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { [self.resultData appendData:data]; } //完成响应 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { if (error == nil) { NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.resultData options:NSJSONReadingAllowFragments error:nil]; NSLog(@"%@", dic); } } POST . block - (IBAction)post:(id)sender { //使用block回调的方式 //使用系统提供的全局的 NSURLSession 对象, 是一个单例 NSURLSession *session = [NSURLSession sharedSession]; //创建一个地址的字符串 NSString *urlString = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"; NSURL *url1 = [NSURL URLWithString:urlString]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url1]; NSString *postString = @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"; NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding]; [request setHTTPMethod:@"POST"]; [request setHTTPBody:postData]; NSURLSessionTask *task1 = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { if (error == nil) { NSDictionary *dic1 = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; NSLog(@"dic1 ==== %@", dic1); } }]; //NSURLSession 的所有任务默认是挂起的,所以一定要调用resume方法, 让任务开始. [task1 resume]; } GET . BLOCK - (IBAction)get:(id)sender { //使用block回调的方式 //使用系统提供的全局的 NSURLSession 对象, 是一个单例 NSURLSession *session = [NSURLSession sharedSession]; //创建一个地址的字符串 NSString *urlString = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"; NSURL *url = [NSURL URLWithString:urlString]; // NSURLSession 是基于任务的, 所以所有的东西都要放在任务里, NSURLSessionTask 就是NSURLSession的任务执行对象 NSURLSessionTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { if (error == nil) { NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; NSLog(@"dic ==== %@", dic); } }]; //NSURLSession 的所有任务默认是挂起的,所以一定要调用resume方法, 让任务开始. [task resume]; } GET 代理 - (IBAction)get:(id)sender { // NSURLSession代理的异步操作 // NSURLSession代理人的属性是只读的. // 一参 :会话模式 // 二参 :代理人 // 三参 :代理方法在哪个线程中进行 // 默认的会话模式.利用代理实现回调.代理人设置为self(自身的类),设置在主线程中进行. NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]]; NSURL *url = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"]; // NSURLSessionTask 的子类 NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url];//没有代理的回调 [dataTask resume]; } //服务器开始响应 - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler { //NSURLSession的代理协议里面, 必须设置允许继续请求, 才会继续响应服务器. 获取到数据.吗; completionHandler(NSURLSessionResponseAllow); self.resultData = [NSMutableData data]; } //接收到数据 - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { [self.resultData appendData:data]; } //完成响应 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { if (error == nil) { NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.resultData options:NSJSONReadingAllowFragments error:nil]; NSLog(@"%@", dic); } }
原文:http://www.cnblogs.com/fubaodong/p/5371197.html