原生 NSURL 网络请求 GET POST

来源:互联网 发布:桃源网络硬盘 编辑:程序博客网 时间:2024/05/29 07:58


转自:http://blog.csdn.net/qq_25475307/article/details/48437767


HTTP : 是应用层的网络传输协议,对于http的请求方式 包括两种:GET 和 POST , 链接方式也包括两种 同步链接 和 异步链接 GET 和 POST 请求的区别: 1:GET请求 : 服务器的地址 和 请求参数都会出现在请求接口中,也就是说 服务器地址和请求参数共同组成了请求借口, 然而POST请求,请求参数不会出现在请求接口中,而是作为请求体提交给服务器. 2:因为GET请求的请求参数 会出现在请求接口中,所有信息容易被捕获,安全性低,而POST请求的请求参数封装在请求体中,作为二进制流进行传输,安全性高, 3:GET请求的请求接口中有请求参数,而对于请求接口我们有字节限制,这样导致GET请求有一定的局限性. 所以对于GET请求只能上传小型数据,而对于POST请求,请求体理论上可以无限大,所以,一般来说,从服务器请求数据用GET 上传数据用POST,两种请求方式:都能给服务器传输数据 不同点: 1 、给服务器传输数据的⽅式: GET :通过网址字符串 。 POST :通过 data 2 、传输数据的⼤小: GET :网址字符串最多 255 字节 。 POST :使⽤ NSData ,容量超过 1G 3 、安全性 : GET :所有传输给服务器的数据,显⽰示在⺴址里,类似于密码的明⽂输入,直接可⻅。 POST :数据被转成 NSData( ⼆进制数据 ) ,类似于密码的密⽂输⼊,⽆法直接读取。同步异步连接的区别: 同步连接:程序容易出现卡死现象 异步连接:等待数据返回。 界面更加流畅 异步联接有两种实现⽅式: (1)设置代理,接收数据 (2)实现 block服务器端 PHP 简单接⼝ PHP 中使⽤不同的函数获取数据,⽀持不同的请求方式: (1)GET 请求:使⽤GET[“key”]获取数据网址中的数据(2)POST请求:使⽤_POST[“key”] 获取上传 data 中的数据 (3)GET、POST 请求:使⽤ $_REQUEST[“key”] 获取数据在 iOS 平台使⽤ NSURL 、 NSURLRequest 等对象完成与接⼝的交互⺴络请求的步骤: 1 、 NSURL ; 2 、 NSURLRequest ; 3 、 NSURLConnection ; 4 、处理 Error 或者返回数据代码部分:

#define kPicURL @"http://image.zcool.com.cn/56/13/1308200901454.jpg"#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 kTuDouURL @"http://api.tudou.com/v3/gw?method=album.channel.get&appKey=myKey&format=xml&channel=c&pageNo=1&pageSize=15"#define kTuDouURLPost @"http://api.tudou.com/v3/gw?"====================================================== 代码:@interfaceViewController ()<NSURLConnectionDataDelegate>@property (retain, nonatomic) IBOutlet UIImageView *ImageView;@property (nonatomic,retain)NSMutableData *data; //用来接收,拼接每一次数据@end@implementation ViewController//同步GET- (IBAction)synGET:(id)sender {    //1: 创建url对象        //(1)创建网址字符串        NSString *urlStr = [NSString stringWithFormat:@"%@",kPicURL];  //图片          //NSString *urlStr = [NSString stringWithFormat:@"%@",kNewsURL];  //新闻        //(2).再编码        NSString *newStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];        //(3)创建url        NSURL *url = [NSURL URLWithString:newStr];    //2: 创建request对象    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);   // self.ImageView.image = [UIImage imageWithData:data];    //解析新闻    NSDictionary *newsDic = [NSJSONSerialization JSONObjectWithData:data options:5 error:nil];    NSLog(@"%@",newsDic);}同步POST POST请求用NSMutableURLRequest创建可变请求对象 目的是为了追加HTTPBody- (IBAction)synPOST:(id)sender {    //1:创建URl对象      //(1)创建网址字符串    //post请求只要网址    NSString *urlStr = [NSString stringWithFormat:@"%@",kTuDouURLPost];      //(2)创建url对象    NSURL *url = [NSURL URLWithString:urlStr];    //2:创建可变请求对象    NSMutableURLRequest *muRequest = [NSMutableURLRequest requestWithURL:url];    //3:设置请求体    //参数    NSString *paraStr = @"method=album.channel.get&appKey=myKey&format=json&channel=c&pageNo=1&pageSize=15";    //把请求参数封装到NSData    NSData *data = [paraStr dataUsingEncoding:NSUTF8StringEncoding];    [muRequest setHTTPBody:data];    //设置请求方式    [muRequest setHTTPMethod:@"POST"];    //4:请求    NSData *data1 = [NSURLConnection sendSynchronousRequest:muRequest returningResponse:nil error:nil];    //解析    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data1 options:0 error:nil];    NSLog(@"%@",dic);}异步GET- (IBAction)asynGET:(id)sender {    //1 创建url对象    //(1)创建网址字符串    NSString *urlStr = [NSString stringWithFormat:@"%@",kPicURL];    //(2)再编码 //防止存在中文    NSString *newStr  = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];    //(3)创建对象    NSURL *url = [NSURL URLWithString:newStr];    //2 创建request对象    NSURLRequest *reQuest = [NSURLRequest requestWithURL:url];    //3 请求 并设置代理    [NSURLConnection connectionWithRequest:reQuest delegate:self];    //当你返回或者不请求数据时候 取消    //NSURLConnection *connection = [NSURLConnection connectionWithRequest:reQuest delegate:self];    //取消请求    //[connection cancel];    //使用Block发送异步请求  与下面 数据加载完成 是同一个时机  一般能用代理的地方就能用block  能用block的地方都能用代理  但是block请求因为没有返回值无法获取NSURLConnection对象    [NSURLConnection sendAsynchronousRequest:reQuest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {        //数据操作//        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];//        NSLog(@"%@",dic);        _ImageView.image = [UIImage imageWithData:data];    }];}异步POST- (IBAction)asynPOST:(id)sender {    //1 创建url    NSURL *url = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?"];    //2 创建可变的请求对象    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];    //3 设置请求体    NSString *paraStr =  @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";    //把参数封装到NSData    NSData *bodydata = [paraStr dataUsingEncoding:NSUTF8StringEncoding];    [request setHTTPBody:bodydata];    //设置请求方式    [request setHTTPMethod:@"POST"];    //4 请求 并设置代理    [NSURLConnection connectionWithRequest:request delegate:self];}#pragma mark - NSURLConmectionDtaDelegate//链接到服务器- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{//初始化data    if (_data == nil) {           self.data = [NSMutableData data];    }}//接收数据-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{//拼接数据    [_data appendData:data];    _ImageView.image = [UIImage imageWithData:_data];}//结束 数据加载完成-(void)connectionDidFinishLoading:(NSURLConnection *)connection{    //数据请求完成 进行数据的处理    NSDictionary *newsDic = [NSJSONSerialization JSONObjectWithData:_data options:0 error:nil];    NSLog(@"%@",newsDic);    }


0 0
原创粉丝点击