NSURL 请求网络数据

涉及到de

http://www.haoservice.com/docs/6

Get请求

发送请求URL数据如下

http://apis.haoservice.com/weather?cityname=%E5%8C%97%E4%BA%AC&key=90df05e06bb64ab4ae4d8c5ec4ec1f72

粘贴到浏览器可以获得类似以下的json串

{"error_code":0,"reason":"成功","result":{"sk": {"temp":"26","wind_direction":"东风","wind_strength":"2 级","humidity":"57","time":"11:02"},"today":{"city":"北京","date_y":"2015年 08月23日","week":"星期日","temperature":"20~28","weather":"雷阵 雨","fa":"04","fb":"02","wind":"无持续风向 微风","dressing_index":"热","dressing_advice":"天气热,建议着短裙、短裤、短薄外套、T恤等夏季服 装。","uv_index":"弱","comfort_index":"--","wash_index":"不 宜","travel_index":"较不宜","exercise_index":"较不 宜","drying_index":"--"},"future":[{"temperature":"19~29","weather":"多 云","fa":"01","fb":"01","wind":"无持续风向 微风","week":"星期一","date":"20150824"},{"temperature":"20~30","weather":"多 云","fa":"01","fb":"01","wind":"无持续风向 微风","week":"星期二","date":"20150825"},{"temperature":"20~28","weather":"多 云","fa":"01","fb":"01","wind":"无持续风向 微风","week":"星期三","date":"20150826"},{"temperature":"19~28","weather":"阵 雨","fa":"03","fb":"01","wind":"无持续风向 微风","week":"星期四","date":"20150827"},{"temperature":"20~28","weather":" 阴","fa":"02","fb":"02","wind":"无持续风向 微风","week":"星期五","date":"20150828"},{"temperature":"20~27","weather":" 阴","fa":"02","fb":"02","wind":"无持续风向 微风","week":"星期六","date":"20150829"}]}}



发送异步请求

 方法1,block


 NSString *urlStr= [NSString stringWithFormat:@"http://apis.haoservice.com/weather?cityname=%@&key=%@",@"北京",@"90df05e06bb64ab4ae4d8c5ec4ec1f72"];
    
    // 转码
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    // URL里面不能包含中文
    NSURL *url = [NSURL URLWithString:urlStr];
    
    // 2.2.创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; // 默认就是GET请求
    request.timeoutInterval = 5; // 设置请求超时
    
    // 2.3.发送请求
    NSOperationQueue *queue = [NSOperationQueue mainQueue];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {  // 当请求结束的时候调用 (拿到了服务器的数据, 请求失败)

        if (data) { // 请求成功

            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSLog(@"dict is %@",dict);

        } else { // 请求失败
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"网络不给力,请稍后再试" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];

            [alert show];
        }
    }];


方法2,设置代理

需要声明代理 <NSURLConnectionDataDelegate>

设置和实现代理方法

-(void)sendAsynRequestWithDelegate{
    NSString *urlStr= [NSString stringWithFormat:@"http://apis.haoservice.com/weather?cityname=%@&key=%@",@"北京",@"90df05e06bb64ab4ae4d8c5ec4ec1f72"];
    
    // 转码
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    // URL里面不能包含中文
    NSURL *url = [NSURL URLWithString:urlStr];
    
    // 2.2.创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; // 默认就是GET请求
    request.timeoutInterval = 5; // 设置请求超时

  
   NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
    [conn start]; // 异步执行
    
    }
    
    #pragma mark - NSURLConnectionDataDelegate 代理方法
/**
 *  请求错误(失败)的时候调用(请求超时\断网\没有网, 一般指客户端错误)
 */
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{

    NSLog(@"connection:didFailWithError:");
   
}

/**
 *  当接受到服务器的响应(连通了服务器)就会调用
 */
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{


   NSLog(@"connection:didReceiveResponse:");
 
    
    // 初始化数据
    self.responseData = [NSMutableData data];
}

/**
 *  当接受到服务器的数据就会调用(可能会被调用多次, 每次调用只会传递部分数据)
 */
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"connection:didReceiveData:");
    NSLog(@"data is %@",data);

    // 拼接(收集)数据
    [self.responseData appendData:data];
}


post请求


连接本地服务器的post方法

// 2.1.设置请求路径
    NSURL *url = [NSURL URLWithString:@"http://192.168.1.200:8080/MJServer/login"];
    
    // 2.2.创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; // 默认就是GET请求
    request.timeoutInterval = 5; // 设置请求超时
    request.HTTPMethod = @"POST"; // 设置为POST请求
    
    // 通过请求头告诉服务器客户端的类型
    [request setValue:@"ios" forHTTPHeaderField:@"User-Agent"];
    
    // 设置请求体
    NSString *param = [NSString stringWithFormat:@"username=%@&pwd=%@", username, pwd];
    request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];
    
    // 2.3.发送请求
    NSOperationQueue *queue = [NSOperationQueue mainQueue];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {  // 当请求结束的时候调用 (拿到了服务器的数据, 请求失败)
        // 隐藏HUD (刷新UI界面, 一定要放在主线程, 不能放在子线程)
        [MBProgressHUD hideHUD];
        
        /**
         解析data :
         {"error":"用户名不存在"}
         {"error":"密码不正确"}
         {"success":"登录成功"}
         */
        if (data) { // 请求成功
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSString *error = dict[@"error"];
            if (error) { // 登录失败
                [MBProgressHUD showError:error];
            } else { // 登录成功
                NSString *success =  dict[@"success"];
                [MBProgressHUD showSuccess:success];
            }
        } else { // 请求失败
            [MBProgressHUD showError:@"网络繁忙, 请稍后再试"];
        }
    }];


你可能感兴趣的:(NSURL 请求网络数据)