创建网络get请求

两种常用方式
1、异步请求

// 0.根据用户名和密码拼接URL
    // 创力url:
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:
@"http://122.33.44.55:8586/login_check_byPhone?userName=%@&passWord=%@",userName,pwd]];
    //NSLog(@"url:%@",url);
    
    // 1.创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    // 2.发送请求,创建一个子线程进行监控服务器响应的数据
   [NSURLConnection sendAsynchronousRequest:request  //发送请求
                                       queue:[[NSOperationQueue alloc] init] //创建一个子线程
                           completionHandler:^(NSURLResponse * _Nullable //回调Block  返回的头
                                               response, NSData * _Nullable data, //返回的数据体
                                               NSError * _Nullable connectionError) { //返回的错误
        
        // 3.响应数据解析
        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@",str);
        
        // HUD必须要在主线程才能进行操作
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            if ([str containsString:@"success"]) {
                [SVProgressHUD showSuccessWithStatus:@"登陆成功"];
            }else{
                [SVProgressHUD showErrorWithStatus:@"登陆失败"];
            }
        }];
    }];

2、代理方法

// 创力url:
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=123"];
    //NSLog(@"url:%@",url);
    
    // 1.创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    // 2.创建请求连接
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

#pragma mark - NSURLConnectionDataDelegate  常用的几个代理方法
/**
 *  请求失败
 *
 *  @param connection
 *  @param error
 */
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"%s,%d-----%@",__func__,__LINE__,error);
}

/**
 *  开始接收数据,如果数据比较大,会多次调用该函数
 *
 *  @param connection
 *  @param data
 */
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%s,%d----%@",__func__,__LINE__,str);
    
}

/**
 *  接收服务器的响应
 *
 *  @param connection
 *  @param response
 */
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    NSLog(@"%s,%d----%@",__func__,__LINE__,response);
    
}

/**
 *  数据接收完成后调用
 *
 *  @param connection
 */
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSLog(@"%s,%d",__func__,__LINE__);
    
}

你可能感兴趣的:(创建网络get请求)