使用NSURLConnection发送网络请求

NSURLRequest

  • 用于保存请求地址/请求头/请求体
  • 默认情况下NSURLRequest会自动给我们设置好请求头
  • request默认情况下就是GET请求

NSURLConnection

NSURLConnection获取网络数据有三种方式:

1. 通过URL同步的方式获取

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://m.baidu.com"]];

    NSURLResponse *response = nil;
    NSError *error = nil;
    
    /*
     第一个参数: 需要请求的对象
     第二个参数: 服务返回给我们的响应头信息
     第三个参数: 错误信息
     返回值: 服务器返回给我们的响应体
     */
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];    

注意:该方法会阻塞主线程,必须保证该方法不是在主线程调用的,否则会影响用户体验。

2. 通过URL异步回调block的方式获取

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://m.baidu.com"]];

    /*
     第一个参数: 需要请求的对象
     第二个参数: 回调block的队列, 决定了block在哪个线程中执行
     第三个参数: 回调block
     */
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

        NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    }];   

3. 通过NSURLRequest代理方法获取

- (void)viewDidLoad {
    [super viewDidLoad];

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://m.baidu.com"]
                                             cachePolicy:NSURLRequestUseProtocolCachePolicy
                                         timeoutInterval:30];

    // 初始化“receivedData”保存接收的数据
    self.receivedData = [NSMutableData dataWithCapacity:0];

    // 创建connection对象
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    if (!conn) {
        self.receivedData = nil;

        // 通知用户连接失败
    }
}

只要调用 initWithRequest:delegate:就会向网络发送请求,不过可以在connectionDidFinishLoading:connection:didFailWithError:中发送cancel消息来取消。

当接受到服务器返回的回应后,会调用代理方法connection:didReceiveResponse:,在这个方法中可以获得NSURLResponse对象,里面包含了一些即将要从服务器接收数据的一些基本信息,比如数据的长度,MIME类型等。

/*
 只要接收到服务器的响应就会调用
 response:响应头
 */
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"type:%@", response.MIMEType);
    NSLog(@"fileName:%@", response.suggestedFilename);
}

接收到服务器返回的数据时调用(该方法可能调用一次或多次)
data: 服务器返回的数据(当前这一次传递给我们的, 并不是总数))

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.receivedData appendData:data];
}

请求错误时调用(请求超时)

- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error
{

    // 释放数据对象

    self.connection = nil;
    self.receivedData = nil;

    // 通知用户
    NSLog(@"连接失败! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}

请求完成

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{

    NSLog(@"Succeeded! Received %lu bytes of data",[self.receivedData length]);

    // 释放数据对象

    self.connection = nil;
    self.receivedData = nil;
}

POST##

发送POST请求

    // 1.创建一个URL
    NSURL *url = [NSURL URLWithString:@"http://www.helloworld.com/login"];

    // 2.根据URL创建NSURLRequest对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // 2.1设置请求方式
    // 注意: POST一定要大写
    request.HTTPMethod = @"POST";
    // 2.2设置请求体
    // 注意: 如果是给POST请求传递参数: 那么不需要写?号
    request.HTTPBody = [@"username=apple&pwd=123&type=JSON" dataUsingEncoding:NSUTF8StringEncoding];

    // 3.利用NSURLConnection对象发送请求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    }];

你可能感兴趣的:(使用NSURLConnection发送网络请求)