---恢复内容开始---

一: 给服务器发送一个简单的GET请求

1.同步

    //  发送一个GET请求给服务器
    
    // 0.请求路径
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=122&pwd=1222"];
    
    //1.通过路径创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];// 默认已经包含请求头了。
    
    
    // 2. 发送请求
      // 这个方法是个阻塞式的方法。
    NSDate *data =  [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    // 将data解析成字符串
    
     NSString *str= [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"----------- data%@",str);
    
}

 

  2.异步请求

 

    //  发送一个异步的GET请求给服务器
    
    // 0.请求路径
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=122&pwd=1222"];
    
    //1.通过路径创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];// 默认已经包含请求头了。
    
    // 2.创建一个线程去发送请求。
    
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {// 当请求在新的线程中发送并返回了数据data后会来到这个block

        NSString *str= [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"----------- data%@",str);
        NSLog(@"%@",[NSThread currentThread]);
        
    }];
    
    NSLog(@"------end---");

打印结果:

可以发现返回数据后,Block执行在线程3,而线程2是因为请求是异步的,去执行请求了。

 

 

 

 

---恢复内容结束---