http网络编程

流程
一.创建一个请求
1,需要一个NSURL对象
2,请求课分为GET请求,POST请求,DELETE请求,PUT请求,常用的是GET,POST请求.创建你NSURLRequest的时候 默认的请求方式是GET
二.建立网络链接 获取数据
1.使用NSURLConnection类 创建链接,链接可分为同步链接和异步链接
三.使用数据(比如,对数据及诶西,或者把数据转换成图片)
1.获得数据之后,要使用数据.如何使用数据,要看是什么数据.无论同步链接还是异步链接,获得数据都使用NSDate存储.

get请求

#pragma mark  ---------get请求------
NSString *str = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
    //Get 请求方式 特点:请求的参数直接跟在URL后面,实现了当前的网址更加完整.使当前的网址更加完整
    //将Str转化为一个url对象
    NSURL *url = [NSURL URLWithString:str];
    //创建一个请求对象,包含要请求的信息,
//    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //NSURLRequestCachePolicy 缓存策略枚举类型   NSTimeInterval请求时间间隔 整型
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];

post请求

#pragma mark  --------POST请求--------
    //post是将URL 和 参数分离的一种请求方式
    NSString *str = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
    
    NSURL *url = [NSURL URLWithString:str];
    
    //使用 NSMutableURLRequest 创建对象
    //NSURLRequest 是一个不可变的请求,默认执行的是GET请求.也就是说,通过NSURLRequest无法制定请求方式为POST,因为TA是不可变的.
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    //怎么设置分离之后的参数呢?
    [request setHTTPMethod:@"POST"];//告诉外界我的请求是POST请求
    
    //post方式,把参数放在了httpBody里面,而非放在了url里面.
    [request setHTTPBody:[@"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213" dataUsingEncoding:NSUTF8StringEncoding]];

公用代码部分

// -----begain 公用部分----------
    //将请求发出去 并且返回了一个NSData,也就是我们的数据
    NSURLResponse *response = nil; //因为是**类型 下同 所以下面写 &response
    NSError *error = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];  //同步连接
    
    //NSOperationQueue 多线程 异步连接的方法
//    NSData *date = [NSURLConnection sendAsynchronousRequest:request queue:<#(NSOperationQueue *)#> completionHandler:<#^(NSURLResponse *response, NSData *data, NSError *connectionError)handler#>]
    
    NSLog(@"data is %@",data);
    NSLog(@"response is %@",response);
    NSLog(@"error is %@",error);
    
// -------end--
    //通过之前介绍的Json解析,可以得到我们想要得到的数据
    
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers  error:nil];
    NSArray *array = [dic objectForKey:@"news"];
 posted on 2015-05-09 16:30  ianhao_cn  阅读(255)  评论(0编辑  收藏  举报