NSURLConnection

常用类

  • NSURL:请求地址
  • NSURLRequest:一个NSURLRequest对象就代表一个请求,它包含的信息有
    • 一个NSURL对象
    • 请求方法、请求头、请求体
    • 请求超时
    • … …
  • NSMutableURLRequest:NSURLRequest的子类
  • NSURLConnection
    • 负责发送请求,建立客户端和服务器的连接
    • 发送数据给服务器,并收集来自服务器的响应数据

NSURLConnection的使用步骤

  • 创建一个NSURL对象,设置请求路径
    传入NSURL

  • 创建一个NSURLRequest对象,设置请求头和请求体

  • 使用NSURLConnection发送请求

NSURLConnection发送请求

NSURLConnection常见的发送请求方法有以下几种
  • 同步请求
+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error;
/**
 * 发送同步请求
 */
- (void)sync{

    // 0.请求路径
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=345"];
    //    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/video"];

    // 1.创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    // 2.发送请求
    // sendSynchronousRequest阻塞式的方法,等待服务器返回数据

    NSHTTPURLResponse *response = nil;
    NSError *error = nil;

    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

    // 3.解析服务器返回的数据(解析成字符串)
    NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@ %@", string, response.allHeaderFields);
}
  • 异步请求:根据对服务器返回数据的处理方式的不同,又可以分为2种
    • block回调
    • 代理
//block回调
+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error;
/**
 * 发送异步请求
 */
- (void)async{

    // 0.请求路径
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/video"];

    // 1.创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    // 2.发送请求
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        // 请求完毕会来到这个block
        // 3.解析服务器返回的数据(解析成字符串)
        NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@", string);

        NSHTTPURLResponse *r = (NSHTTPURLResponse *)response;

        NSLog(@"%zd %@", r.statusCode, r.allHeaderFields);

    }];
}
//代理
- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate;
+ (NSURLConnection*)connectionWithRequest:(NSURLRequest *)request delegate:(id)delegate;
- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately;

//在startImmediately = NO的情况下,需要调用start方法开始发送请求
- (void)start;

//成为NSURLConnection的代理,最好遵守NSURLConnectionDataDelegate协议
- (void)delegateAysnc
{
    // 0.请求路径
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it"];

    // 1.创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    // 2.创建连接对象
    //    [[NSURLConnection alloc] initWithRequest:request delegate:self];

    //    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
    //    [conn start];

    [NSURLConnection connectionWithRequest:request delegate:self];

    // 取消
    //    [conn cancel];
}

#pragma mark - <NSURLConnectionDataDelegate> -- being
/**
 * 接收到服务器的响应
 */
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // 创建data对象
    self.responseData = [NSMutableData data];
    NSLog(@"didReceiveResponse");
}


/**
 * 接收到服务器的数据(如果数据量比较大,这个方法会被调用多次)
 */
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // 不断拼接服务器返回的数据
    [self.responseData appendData:data];
    NSLog(@"didReceiveData -- %zd", data.length);
}

/**
 * 服务器的数据成功接收完毕
 */
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"connectionDidFinishLoading");
    NSString *string = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
    NSLog(@"%@", string);

    self.responseData = nil;
}

/**
 * 请求失败(比如请求超时)
 */
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"didFailWithError -- %@", error);
}

创建GET和POST请求

创建GET请求

- (void)get
{
    // 0.请求路径
    NSString *urlStr = @"http://120.25.226.186:32812/login2?username=小码哥&pwd=520it";
    // 将中文URL进行转码
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlStr];

    // 1.创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    // 2.发送请求
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        // 3.解析服务器返回的数据(解析成字符串)
        NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@", string);
    }];
}

创建POST请求

- (void)post
{
    // 0.请求路径
    NSString *urlStr = @"http://120.25.226.186:32812/login2";
    NSURL *url = [NSURL URLWithString:urlStr];

    // 1.创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    request.HTTPBody = [@"username=小码哥&pwd=520it" dataUsingEncoding:NSUTF8StringEncoding];

    // 2.发送请求
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        // 3.解析服务器返回的数据(解析成字符串)
        NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@", string);
    }];
}

NSString和NSData的互相转换

  • NSString -> NSData
NSData *data = [@"520it.com" dataUsingEncoding:NSUTF8StringEncoding];
  • NSData -> NSString
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  //发送请求给服务器,加载右侧的数据
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        params[@"a"] = @"list";
        params[@"c"] = @"subscribe";
        params[@"category_id"] =@(c.id);
        [[AFHTTPSessionManager manager] GET:@"http://api.budejie.com/api/api_open.php" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
            //字典转模型数组
           NSArray *users = [XJQRecommendUser objectArrayWithKeyValuesArray:responseObject[@"list"]];

            //添加当前类别对应的用户组
            [c.users addObjectsFromArray:users];
            //刷新表格
            [self.detailVC reloadData];

        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            [SVProgressHUD showErrorWithStatus:@"加载数据失败"];
        }];

results matching ""

    No results matching ""