iOS·HTTP那点事(1)NSURLConnection

2016-03-05  本文已影响1251人  devRen
参考文献:

Dome地址

WeatherDome:https://github.com/BigTortoise/WeatherDome

注意:

本文以http://www.k780.com/api/weather.future# 天气预报API接口为例,展示NSURLConnection的GET和POST请求。

1.iOS网络层HTTP请求常用的库:

2.HTTP通信过程

3.NSURLConnection常用类

4.GET和POST请求

// 请求路径
NSString *urlString = @"http://api.k780.com:88/?app=weather.future&weaid=1&&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json";
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

// 创建URL
NSURL *url = [NSURL URLWithString:urlString];

// 创建请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

// 设置请求方法(默认就是GET请求)
request.HTTPMethod = @"GET";
// 请求路径
NSString *urlString = @"http://520it.com/图片";
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

// 创建URL
NSURL *url = [NSURL URLWithString:urlString];

// 创建请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

// 设置请求方法
request.HTTPMethod = @"POST";

// 设置请求体
request.HTTPBody = [@"name=张三&pwd=123" dataUsingEncoding:NSUTF8StringEncoding];

5.NSURLConnection的使用步骤

+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error;
// 这个方法是阻塞式的,会在当前线程发送请求
// 当服务器的数据完全返回时,这个方法才会返回,代码才会继续往下执行
+ (void)sendAsynchronousRequest:(NSURLRequest*) request
                          queue:(NSOperationQueue*) queue
              completionHandler:(void (^)(NSURLResponse* response, NSData* data, NSError* connectionError)) handler;
// 会自动开启一个子线程去发送请求
// 当请求完毕(成功\失败),会自动调用handler这个block
// handler这个block会放到queue这个队列中执行
// startImmediately==YES,创建完毕后,自动发送异步请求
- (instancetype)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately;
- (instancetype)initWithRequest:(NSURLRequest *)request delegate:(id)delegate; // 创建完毕后,自动发送异步请求
+ (NSURLConnection*)connectionWithRequest:(NSURLRequest *)request delegate:(id)delegate; // 创建完毕后,自动发送异步请求
[connection start];
// 当接收到服务器的响应时就会调用
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;

// 每当接收到服务器返回的数据时就会调用1次(数据量大的时候,这个方法就会被调用多次)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;

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

// 当请求失败的时候调用
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
[connection cancel];

6.NSString和NSData的互相转换

NSData *data = [@"520it.com" dataUsingEncoding:NSUTF8StringEncoding];
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  //发送请求给服务器,加载右侧的数据
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        params[@"a"] = @"list";
        params[@"c"] = @"subscribe";
        params[@"category_id"] =@(c.id);
        [[AFHTTPSessionManager manager] GET:@"http://api.budejie.com/api/api_open.php" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
            //字典转模型数组
           NSArray *users = [XJQRecommendUser objectArrayWithKeyValuesArray:responseObject[@"list"]];

            //添加当前类别对应的用户组
            [c.users addObjectsFromArray:users];
            //刷新表格
            [self.detailVC reloadData];

        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            [SVProgressHUD showErrorWithStatus:@"加载数据失败"];
        }];

7.Dome演示

//同步请求
- (void)sync
{
    // 请求路径
    NSURL *url = [NSURL URLWithString:@"http://api.k780.com:88/?app=weather.future&weaid=1&&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json"];
    // 创建请求对象
    NSURLRequest *reuqest = [[NSURLRequest alloc] initWithURL:url];
    
    // 发送请求
    // sendSynchronousRequest阻塞式的方法,等待服务器返回数据
    NSHTTPURLResponse *response = nil;
    NSError *error = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:reuqest returningResponse:&response error:&error];
    
    // 解析服务器返回的数据
    NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"---%@", string);  
}


// 异步请求
- (void)async
{
    // 请求路径
    NSURL *url = [NSURL URLWithString:@"http://api.k780.com:88/?app=weather.future&weaid=1&&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json"];
    // 创建请求对象
    NSURLRequest *reuqest = [[NSURLRequest alloc] initWithURL:url];
    
    // 发送请求
    [NSURLConnection sendAsynchronousRequest:reuqest queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        // 解析服务器返回的数据
        NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@", string);
    }];
}
- (void)asyncPost
{
    // 请求路径
    NSURL *url = [NSURL URLWithString:@"http://api.k780.com:88"];
    // 创建请求对象
    NSMutableURLRequest *reuqest = [[NSMutableURLRequest alloc] initWithURL:url];
    // 更改请求方法
    reuqest.HTTPMethod = @"POST";
    // 设置请求体
    reuqest.HTTPBody = [@"app=weather.future&weaid=1&&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json" dataUsingEncoding:NSUTF8StringEncoding];
    //设置请求超时
    reuqest.timeoutInterval = 3;
    // 设置请求头
    // [request setValue:@"iOS 9.0" forHTTPHeaderField:@"User-Agent"];
    // 发送请求
    [NSURLConnection sendAsynchronousRequest:reuqest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError) { // 比如请求超时
            NSLog(@"----请求失败");
        } else {
            NSLog(@"------%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        }
    }];
    
}
运行结果.png

应用程序安全运输了明文HTTP协议(http:/ /)资源负载是不安全的。暂时的异常可以通过您的应用程序的Info.plist文件配置。

解决办法:在iOS9 beta1中,苹果将原http协议改成了https协议,使用 TLS1.2 SSL加密请求数据。

在info.plist中添加
<key>NSAppTransportSecurity</key><dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/></dict>
正确运行结果.png
- (void)delegateAysnc
{
    // 0.请求路径
    NSURL *url = [NSURL URLWithString:@"http://api.k780.com:88/?app=weather.future&weaid=1&&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json"];
    
    // 1.创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    // 2.创建连接对象
    //    [[NSURLConnection alloc] initWithRequest:request delegate:self];
    
    //    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
    //    [conn start];
    
    [NSURLConnection connectionWithRequest:request delegate:self];
    
    // 取消
    //    [conn cancel];
}

#pragma mark - <NSURLConnectionDataDelegate> -- being
/**
 * 接收到服务器的响应
 */
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{

    NSLog(@"didReceiveResponse");
}


/**
 * 接收到服务器的数据(如果数据量比较大,这个方法会被调用多次)
 */
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // 不断拼接服务器返回的数据
       NSLog(@"didReceiveData -- %zd", data.length);
}

/**
 * 服务器的数据成功接收完毕
 */
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"connectionDidFinishLoading");
}

8.注意点

-发送Get请求时可能Url中会有中文,所有最好进行一次转码:

NSURL *url = [NSURL URLWithString:urlStr];
上一篇下一篇

猜你喜欢

热点阅读