NSURLConnection

2016-09-13  本文已影响86人  Mario_ZJ

基本使用

-(void)sendSync
{
        //1.确定请求路径
        NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it&type=XML"];

        //2.创建一个请求对象
        //该方法内部会提供一个默认的请求头信息 | 默认发送的就是GET请求
        NSURLRequest *request = [NSURLRequest requestWithURL:url];

        //3.把请求发送给服务器
        //设置响应对象    NSHTTPURLResponse是NSURLResponse的子类
        NSHTTPURLResponse *response = nil;
        NSError *error = nil;

        /*
        第一个参数:请求对象
        第二个参数:响应头信息,当该方法执行完毕之后,该参数被赋值
        第三个参数:错误信息,如果请求失败,则error有值
        */
        //该方法是阻塞式的,会卡住线程
        NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

        //4.解析服务器返回的数据
        NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
}
-(void)sendAsync
{
       //1.确定请求路径
        NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it"];

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

        //3.把请求发送给服务器,发送一个异步请求
        /*
        第一个参数:请求对象
        第二个参数:回调方法在哪个线程中执行,如果是主队列则block在主线程中执行,非主队列则在子线程中执行
        第三个参数:completionHandlerBlock块:接受到响应的时候执行该block中的代码
                response:响应头信息
                data:响应体
                connectionError:错误信息,如果请求失败,那么该参数有值
             */
        [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse * __nullable response, NSData * __nullable data, NSError * __nullable connectionError) {

            //请求失败返回的connectionError才会有值,不是看输入的用户名和密码是不是正确
            if (connectionError == nil) {
                  //4.解析服务器返回的数据
                  NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
                  //转换并打印响应头信息
                  NSHTTPURLResponse *r = (NSHTTPURLResponse *)response;
                  NSLog(@"--%zd---%@--",r.statusCode,r.allHeaderFields);
        }
        }];
}
         1.当接收到服务器响应的时候调用
         //第一个参数connection:监听的是哪个NSURLConnection对象
         //第二个参数response:接收到的服务器返回的响应头信息
        - (void)connection:(nonnull NSURLConnection *)connection didReceiveResponse:(nonnull NSURLResponse *)response

         2.当接收到数据的时候调用,该方法会被调用多次
         //第一个参数connection:监听的是哪个NSURLConnection对象
         //第二个参数data:本次接收到的服务端返回的二进制数据(可能是片段)
        - (void)connection:(nonnull NSURLConnection *)connection didReceiveData:(nonnull NSData *)data

         3.当服务端返回的数据接收完毕之后会调用
         //通常在该方法中解析服务器返回的数据
        -(void)connectionDidFinishLoading:(nonnull NSURLConnection *)connection

         4.当请求错误的时候调用(比如请求超时)
         //第一个参数connection:NSURLConnection对象
         //第二个参数:网络请求的错误信息,如果请求失败,则error有值
        - (void)connection:(nonnull NSURLConnection *)connection didFailWithError:(nonnull NSError *)error
字符串截取相关方法
        - (NSRange)rangeOfString:(NSString *)searchString;
        - (NSString *)substringWithRange:(NSRange)range;
-(void)post{
            //1.创建访问饿url路径
            //注意:以POST方式发送的请求的url没有"?"
            NSURL * url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"];
          
            //2.创建请求体
            //注意:要是想要设置发送请求方式为POST,就需要是可变的request
            NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
           //2.1设置发送请求的方式为POST
            request.HTTPMethod = @"POST";
           //2.2设置请求体
            request.HTTPBody = [@"username=520it&pwd=520&type=JSON" dataUsingEncoding:NSUTF8StringEncoding];
            //2.3设置请求时间
            request.timeoutInterval = 15;
            //2.4设置请求头中的信息
            //    [request setValue:@"iOS 10.1" forHTTPHeaderField:@"User-Agent"];

            //3.发送请求
            [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
       
            //4.解析服务器返回的数据
                    if (connectionError) {
                        NSLog(@"--请求失败-");
                    }else{
                        NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
                    }
    }];
}

URL中文转码

**转码的方法 : **stringByAddingPercentEscapesUsingEncoding:
**原因 : **URL是不支持中文, 因此如果URL字符串中包含中文那么在发送请求之前需要 对URL进行中文转码
**注意 : **浏览器中的 http 的链接有时候可以看到有中文, 其实URL内部已经做了转 码处理
**如何对URL进行转码 : **stringByAddingPercentEscapesUsingEncoding
**建议 : **不管有没有中文字符, 都写上转码, 这样扩展性比较好

//获取url的字符串
NSString *urlStr = @"http://120.25.226.186:32812/login2?username=小码哥&pwd=520it";
    NSLog(@"%@",urlStr);
    //中文转码操作
    urlStr =  [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"%@",urlStr);
//根绝转码后的url字符串创建NSURL对象
    NSURL *url = [NSURL URLWithString:urlStr];

NSURLConnection和Runloop

1 两种为NSURLConnection设置代理方式的区别

    //第一种设置方式:
    //通过该方法设置代理,会自动的发送请求
    // [[NSURLConnection alloc]initWithRequest:request delegate:self];

    //第二种设置方式:
    //设置代理,startImmediately为NO的时候,该方法不会自动发送请求
    NSURLConnection *connect = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:NO];
    //手动通过代码的方式来发送请求
    //注意该方法内部会自动的把connect添加到当前线程的RunLoop中在默认模式下执行
    [connect start];

2 如何控制代理方法在哪个线程调用

    //说明:默认情况下,代理方法会在主线程中进行调用(为了方便开发者拿到数据后处理一些刷新UI的操作不需要考虑到线程间通信)
    //设置代理方法的执行队列
    [connect setDelegateQueue:[[NSOperationQueue alloc]init]];

3 开子线程发送网络请求的注意点,适用于自动发送网络请求模式

    //在子线程中发送网络请求-调用startf方法发送
    -(void)createNewThreadSendConnect1
    {
        //1.创建一个非主队列
        NSOperationQueue *queue = [[NSOperationQueue alloc]init];

        //2.封装操作,并把任务添加到队列中执行
        [queue addOperationWithBlock:^{

            NSLog(@"%@",[NSThread currentThread]);
            //2-1.确定请求路径
            NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=dd&pwd=ww&type=JSON"];

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

            //2-3.使用NSURLConnection设置代理,发送网络请求
            NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];

            //2-4.设置代理方法在哪个队列中执行,如果是非主队列,那么代理方法将再子线程中执行
            [connection setDelegateQueue:[[NSOperationQueue alloc]init]];

            //2-5.发送网络请求
            //注意:start方法内部会把当前的connect对象作为一个source添加到当前线程对应的runloop中
            //区别在于,如果调用start方法开发送网络请求,那么再添加source的过程中,如果当前runloop不存在
            //那么该方法内部会自动创建一个当前线程对应的runloop,并启动。
            [connection start];

        }];
    }

    //在子线程中发送网络请求-自动发送网络请求
    -(void)createNewThreadSendConnect2
    {
        NSLog(@"-----");
        //1.创建一个非主队列
        NSOperationQueue *queue = [[NSOperationQueue alloc]init];

        //2.封装操作,并把任务添加到队列中执行
        [queue addOperationWithBlock:^{

            //2-1.确定请求路径
            NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=dd&pwd=ww&type=JSON"];

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

            //2-3.使用NSURLConnection设置代理,发送网络请求
            //注意:该方法内部虽然会把connection添加到runloop,但是如果当前的runloop不存在,那么不会主动创建。
            NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];

            //2-4.设置代理方法在哪个队列中执行,如果是非主队列,那么代理方法将再子线程中执行
            [connection setDelegateQueue:[[NSOperationQueue alloc]init]];

            //2-5 创建当前线程对应的runloop,并开启(因为这个方法不会自动创建一个线程供NSURLConnection对象发送网络请求)
           [[NSRunLoop currentRunLoop]run];
        }];
    }
上一篇 下一篇

猜你喜欢

热点阅读