UI - RequestNetWork
2015-10-18 15:38
417 查看
<ViewController.h>
<ViewController.m>
<RequestHandle.h>
<RequestHandle.m>
#import <UIKit/UIKit.h> @interface ViewController : UIViewController @end
<ViewController.m>
#import "ViewController.h" #import "RequestHandle.h" #define kNewsURL @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213" #define kPicURL @"http://image.zcool.com.cn/56/13/1308200901454.jpg" #define kTuDouURL @"http://api.tudou.com/v3/gw?method=album.channel.get&appKey=myKey&format=xml&channel=c&pageNo=1&pageSize=15" @interface ViewController ()<NSURLConnectionDataDelegate,RequestHandleDelegate> @property (retain, nonatomic) IBOutlet UIImageView *imageView; @property (nonatomic,retain)NSMutableData *data;//存储获取数据 @end @implementation ViewController /* HTTP 是应用层的网络传输协议,对 HTTP 请求主要流行的方式有两种 GET 请求以及 POST 请求 GET 请求和 POST 请求区别和联系: 1.GET请求,服务器网址以及参数都会出现在我们网络请求的接口中,也就是说参数会作为请求接口的一部分.而POST请求,在接口中只有服务器网址,而参数会作为请求体交给服务器 2.因为 GET 请求参数会作为接口的一部分出现在接口中,所以信息容易捕获,不安全,而 POST 请求参数会被封装在请求体中,作为二进制数据进行传输,不易捕获,安全性高 3.因为接口有字节限制,虽然从理论上 GET请求 和 POST请求都可以进行请求数据和上传数据,但GET 请求参数会占用字节,所以只能进行小数据上传,而 POST 请求参数在请求体二进制数据中,理论上是无限的,所以,我们一般使用 GET 请求获取数据, POST 请求上传数据 */ //同步 GET - (IBAction)synGET:(id)sender { //1.创建 NSURL 对象 //(1)获取 urlString NSString *urlString = [NSString stringWithFormat:kPicURL]; //(2)重新编码 NSString *newStr = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:newStr]; //2.创建 NSURLRequeste 请求对象 NSURLRequest *request = [NSURLRequest requestWithURL:url]; //3.请求数据 NSURLResponse *response = nil; NSError *error = nil; NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; NSLog(@"---%@---",response); NSLog(@"===%@===",error); NSLog(@"***%@***",data); //解析 // NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; // NSLog(@"###%@###",dic); self.imageView.image = [UIImage imageWithData:data]; } //同步 POST - (IBAction)synPOST:(id)sender { //1.创建 NSURL 对象 NSString *urlString = [NSString stringWithFormat:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"];//一般的,?之前是网址,?之后是参数,这里写入的是网址 NSURL *url = [NSURL URLWithString:urlString]; //2.请求可变请求对象 NSMutableURLRequest *muRequest = [NSMutableURLRequest requestWithURL:url]; //3.设置请求体和请求方式 //(1)创建请求参数 NSString *parameterStr = [NSString stringWithFormat:@"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"];//参数部分 //(2)将请求参数封装成对象 NSData *paraData = [parameterStr dataUsingEncoding:NSUTF8StringEncoding]; //设置请求体和请求方式 [muRequest setHTTPBody:paraData]; [muRequest setHTTPMethod:@"POST"]; //4.请求数据 NSData *data = [NSURLConnection sendSynchronousRequest:muRequest returningResponse:nil error:nil]; //数据处理 NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; NSLog(@"%@",dic); } //异步 GET - (IBAction)asynGET:(id)sender { //1.创建 NSURL对象 //(1)创建 urlString NSString *urlString = [NSString stringWithFormat:kPicURL]; //(2)重新编码 NSString *newString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; //(3)创建 url NSURL *url = [NSURL URLWithString:newString]; //2.创建请求对象 NSURLRequest *request = [NSURLRequest requestWithURL:url]; //3.请求数据 //a 使用代理方法回调进行异步网络请求 // [NSURLConnection connectionWithRequest:request delegate:self];//此代理需要服从<NSURLConnectionDataDelegate>协议,其中又服从<NSURLConnectionDelegate> //b 使用block进行异步网络请求 [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { //当数据获取成功时执行 self.imageView.image = [UIImage imageWithData:data]; }]; } //异步 POST - (IBAction)asynPOST:(id)sender { //创建 NSURL对象 NSString *urlString = [NSString stringWithFormat:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"]; NSURL *url = [NSURL URLWithString:urlString]; //2.创建请求对象 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; //3.设置请求体和请求方式 //(1)获取参数字符串 NSString *paraStr = [NSString stringWithFormat:@"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"]; //(2)转化为 NSData 对象 NSData *paraData = [paraStr dataUsingEncoding:NSUTF8StringEncoding]; request.HTTPBody = paraData; request.HTTPMethod = @"POST"; //4.请求数据 //a 代理方法回调 [NSURLConnection connectionWithRequest:request delegate:self]; //b 使用 block 进行异步网络请求 [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; NSLog(@"%@",dic); }]; } //================================NSURLConnectionDataDelegate========================= //连接到服务器 -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSLog(@"建立链接"); //当连接到服务器的时候 创建对象 self.data = [NSMutableData data ]; } //获取数据 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { NSLog(@"获取数据"); //将所有数据进行拼接 [self.data appendData:data]; } //完成请求 -(void)connectionDidFinishLoading:(NSURLConnection *)connection { NSLog(@"请求完成"); //数据请求完成 可以进行数据的操作 //异步GET // self.imageView.image = [UIImage imageWithData:_data]; // 异步 POST 解析 NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:_data options:0 error:nil]; NSLog(@"%@",dic); } //请求失败 -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { NSLog(@"请求失败"); } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. [[RequestHandle alloc]initWithURLString:kNewsURL paraString:nil method:@"GET" delegate:self]; } -(void)requestHandle:(RequestHandle *)requestHandle didSucceedWithData:(NSMutableData *)data { NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; NSLog(@"%@",dic); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (void)dealloc { [_imageView release]; [super dealloc]; } @end
<RequestHandle.h>
#import <Foundation/Foundation.h> @class RequestHandle; @protocol RequestHandleDelegate <NSObject> //请求成功 -(void)requestHandle:(RequestHandle *)requestHandle didSucceedWithData:(NSMutableData *)data; //请求失败 -(void)requestHandle:(RequestHandle *)requestHandle didfailWithError:(NSError *)error; @end @interface RequestHandle : NSObject @property (nonatomic,assign)id<RequestHandleDelegate>delegate; @property (nonatomic,retain)NSURLConnection *connection; //初始化方法 -(id)initWithURLString:(NSString *)urlString paraString:(NSString *)paraString method:(NSString *)method delegate:(id<RequestHandleDelegate>)delegate; //取消请求 -(void)cancle; @end
<RequestHandle.m>
#import "RequestHandle.h" @interface RequestHandle ()<NSURLConnectionDataDelegate> @property (nonatomic,retain)NSMutableData *data;//数据存储 @end @implementation RequestHandle //初始化方法 -(id)initWithURLString:(NSString *)urlString paraString:(NSString *)paraString method:(NSString *)method delegate:(id<RequestHandleDelegate>)delegate { if ([super init]) { self.delegate = delegate; //根据 method 进行 GET POST 请求的选择 if ([method isEqualToString:@"GET"]) { //GET 请求 [self requestByGETWithURLString:urlString]; }else if ([method isEqualToString:@"POST"]){ //POST 请求 [self requestByPOSTWithURLString:urlString paraString:paraString]; } } return self; } //GET 请求 -(void)requestByGETWithURLString:(NSString *)urlString { //1.NSURL NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; //2.创建请求对象 NSURLRequest *request = [NSURLRequest requestWithURL:url]; //3.建立连接请求数据 self.connection = [NSURLConnection connectionWithRequest:request delegate:self]; } //取消 GET请求 -(void)cancle { [self.connection cancel]; } //POST 请求 -(void)requestByPOSTWithURLString:(NSString *)urlString paraString:(NSString *)paraString { //1.NSURL NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; //2.创建请求对象 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; //3.请求体和请求方式 NSData *paradata = [paraString dataUsingEncoding:NSUTF8StringEncoding]; request.HTTPBody = paradata; request.HTTPMethod = @"POST"; //4.请求数据 self.connection = [NSURLConnection connectionWithRequest:request delegate:self]; } //=======================================NSURLConnectionDataDelegate================================ //建立连接 -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { self.data = [NSMutableData data]; } //获取数据 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [self.data appendData:data]; } //完成请求 -(void)connectionDidFinishLoading:(NSURLConnection *)connection { if ([self.delegate respondsToSelector:@selector(requestHandle:didSucceedWithData:)]) { //当数据请求完成之后 告知代理调用协议中的方法将数据拿走 [self.delegate requestHandle:self didSucceedWithData:_data]; } } //请求失败 -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { if ([self.delegate respondsToSelector:@selector(requestHandle:didfailWithError:)]) { [self.delegate requestHandle:self didfailWithError:error]; } } @end
相关文章推荐
- iOS:UIAlertController和UIAlertAction的详解
- UI - JSONParser
- HibernateQueryException: ClassNotFoundException: org.hibernate.hql.ast.HqlToken
- 关于LigerUI表单元素的动态替换
- UI - XMLParser
- 【IOS 开发学习总结-OC-55】故事板中 segue 的 push、modal、popover、replace、custom 学习笔记
- UI - Block
- C#中的string与stringbuilder有什么区别
- mysql uuid 性能调优
- String,StringBuffer与StringBuilder的区别
- EasyUI+js实现动态加载导航栏
- IOS基础UI之(六)综合小案例-应用管理
- UI - UITabBarController
- iOS改变UITextField中光标颜色
- org.hibernate.exception.SQLGrammarException: could not execute query错误解决笔记
- UIScrollViewA都PI得知。
- AutoLayout自定义tableViewCell --- Masonry + UITableView+FDTemplateLayoutCell 纯代码实现
- UGUI 里特效的层级
- 第十四篇:cxcore100.dll cv100.dll highgui100.dll libguide40.dll 的驱动安装
- hdu(5504)——GT and sequence