iOS网络通信-NSURLConnection

一、介绍

    NSURLConnection通过提供的 URL request加载url的内容。NSURLConnection仅仅提供开始和取消网络请求,需要你在url 请求对象中自己进行配置。系统提供三个协议,NSURLConnectionDelegate 和 NSURLConnectionDataDelegate便于我们进行更好的控制。

    NSURLConnection类与三个正式协议协同工作:NSURLConnectionDelegate,NSURLConnectionDataDelegate,以及NSURLConnectionDownloadDelegate.为了使用这些协议,其中NSURLConnectionDelegate 协议主要是用来进行证书处理,也处理连接完成。因为在数据传输过程中还处理连接失败,所以所有关于连接的请求都需要实现这个协议。通常不是Newsstand kit 操作,都需要实现NSURLConnectionDataDelegate协议,

二、属性和方法

1、预处理连接请求

+ (BOOL)canHandleRequest:(NSURLRequest * nonnull)request   判断连接请求是否可行。

2、URL请求信息

@property(readonly,copy)NSURLRequest *originalRequest 

@property(readonly,copy)NSURLRequest *currentRequest  获取当前的请求。

3、同步请求

+ (NSData * nullable)sendSynchronousRequest:(NSURLRequest * nonnull)request returningResponse:(NSURLResponse * nullable * nullable)response error:(NSError * nullable * nullable)error

4、异步请求

+ (NSURLConnection * nullable)connectionWithRequest:(NSURLRequest * nonnull)request delegate:(id nullable)delegate

- (instancetype nullable)initWithRequest:(NSURLRequest * nonnull)request delegate:(id nullable)delegate 

- (instancetype nullable)initWithRequest:(NSURLRequest * nonnull)request delegate:(id nullable)delegate startImmediately:(BOOL)startImmediately

+ (void)sendAsynchronousRequest:(NSURLRequest * nonnull)request queue:(NSOperationQueue * nonnull)queue completionHandler:(void (^ nonnull)(NSURLResponse * nullable response, NSData * nullable data, NSError * nullable connectionError))handler

- (void)start   当startImmediately为NO时

5、暂停连接

- (void)cancel

6、调度委托方法

startImmediately为NO时

- (void)scheduleInRunLoop:(NSRunLoop * nonnull)aRunLoop forMode:(NSString * nonnull)mode

- (void)setDelegateQueue:(NSOperationQueue * nullable)queue

- (void)unscheduleFromRunLoop:(NSRunLoop * nonnull)aRunLoop forMode:(NSString * nonnull)mode


三、实际例子


    NSString *urlAddress= @"192.168.2.235/xampp/bl/login.xml";
    NSString *encodeUrl = [urlAddress stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableURLRequest  *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:encodeUrl]];
    request.HTTPMethod = @"POST";
    request.timeoutInterval = 60 ;
    request.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
    BLMultipartForm *form = [[BLMultipartForm alloc] init];
    [form addValue:@"zhangsan" forField:@"username"];
    [form addValue:@"123456" forField:@"password"];
    request.HTTPBody = [form httpBody];
    
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        
        if (connectionError) {
            NSLog(@"%@", connectionError);

        }
        else {
            NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
              NSLog(@"HttpResponseBody %@",responseString);
        }
    }];


   NSString *URLString = @"http://192.168.199.141/xampp/bl/login.xml";
    
    // GET  eg, http://xxxx.com/login.json?username=zhangsan&password=123456
    URLString = [NSString stringWithFormat:@"%@?username=%@&password=%@", URLString, userName, password];
    NSString *encodedURLString
    = [URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *URL = [NSURL URLWithString:encodedURLString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
    request.HTTPMethod = @"GET";
    request.timeoutInterval = 60;
    request.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
    self.URLConnection = [[NSURLConnection alloc] initWithRequest:request
                                                         delegate:self
                                                 startImmediately:YES];


    
    NSString *URLString = @"http://192.168.199.141/xampp/bl/login.xml";
    NSString *encodedURLString
    = [URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *URL = [NSURL URLWithString:encodedURLString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
    request.HTTPMethod = @"POST";
    request.timeoutInterval = 60;
    request.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
    BLMultipartForm *form = [[BLMultipartForm alloc] init];
    [form addValue:userName forField:@"username"];
    [form addValue:password forField:@"password"];
    request.HTTPBody = [form httpBody];
    self.URLConnection = [[NSURLConnection alloc] initWithRequest:request
                                                         delegate:self
                                                 startImmediately:YES];



#pragma mark - NSURLConnectionDataDelegate methods

- (void)connection:(NSURLConnection *)connection
    didReceiveResponse:(NSURLResponse *)response
{
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    if (httpResponse.statusCode == 200) {   // 连接成功
        self.receivedData = [NSMutableData data];
    }else {
        // 请求错误,错误处理。
    }
}

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

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *string = [[NSString alloc] initWithData:self.receivedData
                                             encoding:NSUTF8StringEncoding];
    NSLog(@"%@", string);
    
    BLLoginRequestParser *parser = [[BLLoginRequestParser alloc] init];
//    BLUser *user = [parser parseJson:self.receivedData];
    BLUser *user = [parser parseXML:self.receivedData];
    if ([_delegate respondsToSelector:@selector(requestSuccess:user:)]) {
        [_delegate requestSuccess:self user:user];
    }
    

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"%@", error);
    if ([_delegate respondsToSelector:@selector(requestFailed:error:)]) {
        [_delegate requestFailed:self error:error];
    }
}

   总结: 网络请求的步骤如下:
         1、创建NSURL对象,包含需要请求的URL地址
         2、创建NSURLRequest请求对象,可以在request对象中添加额外数据:header和body相关参数
         3、创建NSURLConnection连接。
     请求中需要根据请求的方法去实现delegate,如果是sendAsynchronousRequest 方法,则可以在block中对结果进行处理。其它的请求则需要实现相关代理方法

1、一般请求成功首先调用此代理方法,返回状态和包头的信息

- (void)connection:(NSURLConnection *)connection
    didReceiveResponse:(NSURLResponse *)response

2、请求失败会调用此方法:

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

3、接收到返回的数据后调用此方法

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data; 

4、完成请求调用方法

- (void)connectionDidFinishLoading:(NSURLConnection *)connection


基本就是按这个模式来,不过2013年后,iOS 7 和 Mac OS X 10.9 Mavericks对 Foundation URL 加载系统的彻底重构,苹果推出NSURLSession来替代NSURLConnection。接下来会讲解一些NSURLSession

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

house.zhang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值