iOS网络编程HTTP解决方案-NSURLConnection-GET请求

1.iOS发送HTTP请求常用技术点

在iOS中,常见的发送HTTP请求的方案有

  1. 苹果原生自带
    NSURLConnection:用法简单,最古老最经典最直接的一种方案【坑比较多】
    NSURLSession:功能比NSURLConnection更加强大,苹果目前比较推荐使用这种技术【2013推出,iOS7开始出的技术】
    CFNetwork:NSURL*的底层,纯C语言

  2. 第三方框架
    ASIHttpRequest:外号“HTTP终结者”,功能极其强大,可惜早已停止更新
    AFNetworking:简单易用,提供了基本够用的常用功能,维护和使用者多
    MKNetworkKit:简单易用,产自三哥的故乡印度,维护和使用者少

为了提高开发效率,企业开发用的基本是第三方框架,兼有对苹果原生自带技术的封装

2.NSURLConnection

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

使用NSURLConnection发送请求的步骤:
1>创建一个NSURL对象,设置请求路径
2>传入NSURL创建一个NSURLRequest对象,设置请求头和请求体
3>使用NSURLConnection发送请求

iOS网络编程HTTP解决方案-NSURLConnection-GET请求_第1张图片
6-NSURLConnection发送HTTP请求.png

苹果SDK提供的相关方法:

NSURLConnection常见的发送请求方法有以下几种

//同步请求
+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error;

//异步请求:根据对服务器返回数据的处理方式的不同,又可以分为2种
//block回调
+ (void)sendAsynchronousRequest:(NSURLRequest*)request  
                          queue:(NSOperationQueue*)queue  
              completionHandler:(void (^)(NSURLResponse* response, NSData* data, NSError* connectionError))handler;
//代理
- (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;
- (void)cancel;//对应终止发送请求

//成为NSURLConnection的代理,最好遵守  协议
// NSURLConnectionDataDelegate协议中的代理方法

//开始接收到服务器的响应时调用
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;

//接收到服务器返回的数据时调用(服务器返回的数据比较大时会调用多次)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;

//服务器返回的数据完全接收完毕后调用
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;

//请求出错时调用(比如请求超时)
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;

3.NSURLConnection使用

3.1发送同步请求

/**
 * 发送同步请求
 */
- (void)sync{
    // 0.请求路径    
    NSURL *url = [NSURL URLWithString:@"http://www.jianshu.com/users/468d1f0192cb/latest_articles"];
    // 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);
}

3.2发送异步请求

/**
 * 发送异步请求
 */
- (void)async{
    NSURL *url = [NSURL URLWithString:@"http://www.jianshu.com/users/468d1f0192cb/latest_articles"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[[NSOperationQueue alloc] init]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                               // 请求完毕会来到这个block
                               // 解析服务器返回的数据(解析成字符串)
                               NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                               NSLog(@"%@", string);
                               
                               NSHTTPURLResponse *r = (NSHTTPURLResponse *)response;
                               NSLog(@"%zd %@", r.statusCode, r.allHeaderFields);
                           }];
}

3.3代理方式

@interface ViewController () 
/** 用来存放服务器返回的数据 */
@property (nonatomic, strong) NSMutableData *responseData;
@end

@implementation ViewController
/**
 * NSURLConnection 代理使用方式
 */
- (void)delegateAysnc{
    NSURL *url = [NSURL URLWithString:@"http://www.jianshu.com/users/468d1f0192cb/latest_articles"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection connectionWithRequest:request delegate:self];
}

/**
 * 接收到服务器的响应
 */
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    NSLog(@"didReceiveResponse");
    self.responseData = [NSMutableData data];
}

/**
 * 接收到服务器的数据(如果数据量比较大,这个方法会被调用多次)
 */
- (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);
}

// didReceiveResponse
// didReceiveData -- 3752
// didReceiveData -- 12131
// didReceiveData -- 3052
// connectionDidFinishLoading
// 打印出的网页代码
// #pragma mark -  -- end
@end
NSURL *url = [NSURL URLWithString:@"http://www.jianshu.com/users/468d1f0192cb/latest_articles"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

// 1.自动发送请求
[NSURLConnection connectionWithRequest:request delegate:self];

// 2.自动发送请求
[[NSURLConnection alloc] initWithRequest:request delegate:self];

// 3.1 手动发送请求
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[conn start];
// 3.2 取消发送请求
[conn cancel];

3.4异步线程执行耗时操作,主线程更新UI

NSString *urlStr = @"http://www.jianshu.com/users/468d1f0192cb/latest_articles";
NSURL *url = [NSURL URLWithString:urlStr];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
                                   queue:[[NSOperationQueue alloc] init]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                           NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                           // 回到主线程
                           [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                              // 把网页显示在webView上
                           }];
                       }];

3.5GET请求多值参数

NSURL *url = [NSURL URLWithString:@"http://www.example.com:8080/weather?place=Beijing&place=Shanghai"];
//{"weathers":[{"city":"Beijing","status":"晴转多云"},{"city":"Shanghai","status":"晴转多云"}]}

你可能感兴趣的:(iOS网络编程HTTP解决方案-NSURLConnection-GET请求)