您的位置:首页 > 理论基础 > 计算机网络

iOS 网络请求

2016-01-12 19:17 369 查看

iOS网络编程

计算机网络

HTTP-(超文本协议)

Https-(安全的超文本协议)  --- 如今用的就是这种方式,网络请求的时候需要配置网络安全



将以下代码插入进去

<key>NSAppTransportSecurity</key>

<dict>

    <key>NSAllowsArbitraryLoads</key>

<true/></dict>

Http常见的两种请求方式:

POST : 1 地址栏中不会有表单请求的参数

             2 参数数量和长度没有限制

GET   :  通常用于从服务器获取数据

             1 将表单请求中的参数拼接在地址中进行传递

             2 参数数量和长度不能超过255字节

安全性:POST安全性高

请求大量数据用Get

提交大量表单数据用Post

iOS网络编程是如何实现的:

NSURL(网络(统一)资源定位符)(网络地址)   

NSURLRequest

NSURLConnection

NSURLConnectionDelegate   

一个典型的网址: http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213 url的正规语法:协议://授权(域名)/资源路径?参数列表(例name=123&sex=男,中间&符号连接)


网络请求  详见思维导图



  网络接口

#define WHGETURL  @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20151124&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"

#define CQPOSTURL @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"

#define CQPOSTBODY @"date=20151124&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"

#pragma mark  GET方式进行同步请求

- (void)GetSyncAction {

    //
网络请求

    // 1
生成URL对象

    NSURL *url = [NSURLURLWithString:WHGETURL];

    // 2
创建请求对象, 绑定URL

    NSMutableURLRequest *request = [[NSMutableURLRequestalloc]
initWithURL:url];

    // 3
发送请求

    NSData *data = [NSURLConnectionsendSynchronousRequest:request
returningResponse:nilerror:nil];

//    NSLog(@"%@", data);

    // Json解析

    NSDictionary *dic = [NSJSONSerializationJSONObjectWithData:data
options:NSJSONReadingAllowFragmentserror:nil];

    

//    NSLog(@"%@", dic[@"news"]);

    NSArray *arr = dic[@"news"];

    

    self.data = [NSMutableArrayarray];

    for (NSDictionary *dicin arr) {

        News *news = [[Newsalloc]
init];

        [news setValuesForKeysWithDictionary:dic];

        [self.dataaddObject:news];

    }

    for (News *newin
self.data) {

        NSLog(@"%@  %@  %ld", new.title, new.NId, new.sequence);

    }

}

#pragma mark  post同步请求

- (void)PostSyncAction {

    //  1
创建URL对象

    NSURL *url = [NSURLURLWithString:CQPOSTURL];

    //  2
创建request对象

    NSMutableURLRequest *request = [[NSMutableURLRequestalloc]
initWithURL:url];

    

    // 3
注意: 与get方式的俩个不同

    // 3.1
设置httpMethod

    [request setHTTPMethod:@"POST"];

    // 3.2
设置HTTPBody,即传递参数

    NSData *data = [CQPOSTBODYdataUsingEncoding:NSUTF8StringEncoding];

    [request setHTTPBody:data];

    // 4
发送同步请求

    NSData *dataRE = [NSURLConnectionsendSynchronousRequest:request
returningResponse:nilerror:nil];

    NSDictionary *dic = [NSJSONSerializationJSONObjectWithData:dataRE
options:NSJSONReadingAllowFragmentserror:nil];

    NSArray *arr = dic[@"news"];

    self.data = [NSMutableArrayarray];

    for (NSDictionary *dicin arr) {

        News *new = [[Newsalloc]
init];

        [new setValuesForKeysWithDictionary:dic];

        [self.dataaddObject:new];

    }

    for (News *newin
self.data) {

        NSLog(@"%@  %@  %ld", new.title, new.NId, new.sequence);

    }

}

#pragma mark  get代理方式进行异步请求

- (void)GETDelegateAsyncAction {

    //  1
创建URL对象

    NSURL *url = [NSURLURLWithString:WHGETURL];

    //  2
创建URLRequest对象

    NSMutableURLRequest *request = [[NSMutableURLRequestalloc]
initWithURL:url];

    //  3
注意!!!!!!同步与异步的不同

    [NSURLConnectionconnectionWithRequest:request
delegate:self];

    

}

//  当收到服务器响应的时候

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

    // 
初始化结果数组

    self.data = [NSMutableArrayarray];

    // 
初始化缓冲水桶

    self.tempData = [NSMutableDatadata];

}

//  接收数据

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

   
//   将读取的部分数据拼接到水桶中

    [self.tempDataappendData:data];

}

//  当所有数据接收完毕的时候

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

   
//  对水桶中所有的数据进行解析

    NSDictionary *dict = [NSJSONSerializationJSONObjectWithData:self.tempDataoptions:NSJSONReadingAllowFragmentserror:nil];

    NSArray *arr = dict[@"news"];

    for (NSDictionary *dicin arr) {

        News *news = [[Newsalloc]
init];

        [news setValuesForKeysWithDictionary:dic];

        [self.dataaddObject:news];

    }

    for (News *newin
self.data) {

        NSLog(@"%@", new.title);

    }

}

#pragma mark  get Block方式实现异步请求

- (void)GETBlockAsyncAction {

    // 1
创建URL对象

    NSURL *url = [NSURLURLWithString:WHGETURL];

    // 2
创建请求对象

    NSMutableURLRequest *request = [[NSMutableURLRequestalloc]
initWithURL:url];

    // 3
发送异步请求

    [NSURLConnection
sendAsynchronousRequest:request queue:[NSOperationQueuemainQueue]
completionHandler:^(NSURLResponse *_Nullable response,
NSData * _Nullable data,
NSError * _Nullable connectionError) {

        NSDictionary *dict = [NSJSONSerializationJSONObjectWithData:data
options:NSJSONReadingAllowFragmentserror:nil];

        NSArray *arr = dict[@"news"];

        self.data = [NSMutableArrayarray];

        for (NSDictionary *dicin arr) {

            News *new = [[Newsalloc]
init];

            [new setValuesForKeysWithDictionary:dic];

            [self.dataaddObject:new];

        }

        for (News *newin
self.data) {

            NSLog(@"%@", new.title);

        }

    }];

    

}

#pragma mark  POST 代理方式实现异步请求

- (void)PostDelegateAsyncActionDe {

    NSURL *url = [NSURLURLWithString:CQPOSTURL];

    NSMutableURLRequest *request = [[NSMutableURLRequestalloc]
initWithURL:url];

    [request setHTTPMethod:@"POST"];

    NSData *data = [CQPOSTBODYdataUsingEncoding:NSUTF8StringEncoding];

    [request setHTTPBody:data];

    [NSURLConnectionconnectionWithRequest:request
delegate:self];

}

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

    self.data = [NSMutableArrayarray];

    self.tempData = [NSMutableDatadata];

}

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

    [self.tempDataappendData:data];

}

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

    NSDictionary *dict = [NSJSONSerializationJSONObjectWithData:self.tempDataoptions:NSJSONReadingAllowFragmentserror:nil];

    NSArray *arr = dict[@"news"];

    for (NSDictionary *dicin arr) {

        News *new = [[Newsalloc]
init];

        [new setValuesForKeysWithDictionary:dic];

        [self.dataaddObject:new];

    }

    for (News *nin
self.data) {

        NSLog(@"%@", n.summary);

    }

}

#pragma mark  POST block方式实现异步请求

- (void)PostBlockAsyncActionBb {

    NSURL *url = [NSURLURLWithString:CQPOSTURL];

    NSMutableURLRequest *request = [[NSMutableURLRequestalloc]
initWithURL:url];

    [request setHTTPMethod:@"POST"];

    NSData *data = [CQPOSTBODYdataUsingEncoding:NSUTF8StringEncoding];

    [request setHTTPBody:data];

    [NSURLConnectionsendAsynchronousRequest:request
queue:[NSOperationQueue
mainQueue] completionHandler:^(NSURLResponse *_Nullable response,
NSData * _Nullable data,
NSError * _Nullable connectionError) {

        NSDictionary *dict = [NSJSONSerializationJSONObjectWithData:data
options:NSJSONReadingAllowFragmentserror:nil];

        NSArray *arr = dict[@"news"];

        self.data = [NSMutableArrayarray];

        for (NSDictionary *dicin arr) {

            News *new = [[Newsalloc]
init];

            [new
setValuesForKeysWithDictionary:dic];

            [self.dataaddObject:new];

        }

        for (News *nin
self.data) {

            NSLog(@"%@", n.title);

        }

    }];

}

由上总结:
GET,POST代理方式实现异步请求时[NSURLConnection connectionWithRequest:request delegate:self];
 

然后代理实现三个方法

GET,POST block方式实现异步请求时[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(N......

iOS9以后的网络请求方法  -- 会话机制

iOS9中只有异步  也分GET,POST请求

iOS9中将网络分为3中类型:

NSURLSessionDataTask

NSURLSessionDownloadsTask

NSURLSessionUploadTask

新版的网络请求是采用多线程的方式实现的

#pragma mark  --  iOS9的新方法进行GET异步请求

- (IBAction)getAction:(UIButton *)sender {

    //  1
创建url

    NSURL *url = [NSURLURLWithString:GETRUL];

    //  2
创建请求对象

    NSMutableURLRequest *request = [[NSMutableURLRequestalloc]
initWithURL:url];

    // 
注意iOS9的不同

    //  3
创建回话

    NSURLSession *session = [NSURLSessionsharedSession];

    NSURLSessionDataTask *task = [sessiondataTaskWithRequest:request
completionHandler:^(NSData *
_Nullable data, NSURLResponse *
_Nullable response,
NSError * _Nullable error) {

        NSDictionary *dic = [NSJSONSerializationJSONObjectWithData:data
options:NSJSONReadingAllowFragmentserror:nil];

        NSLog(@"%@", dic);

    }];

    //  5
开始任务

    [task resume];

}

#pragma mark  --  
使用iOS9的新方法进行post异步请求

- (IBAction)postAction:(UIButton *)sender {

    //  1
创建URL对象

    NSURL *url = [NSURLURLWithString:POSTURL];

    //  2
创建请求对象

    NSMutableURLRequest *request = [[NSMutableURLRequestalloc]
initWithURL:url];

    //  3
设置post属性

    [request setHTTPMethod:@"POST"];

    NSData *data = [POSTBODYdataUsingEncoding:NSUTF8StringEncoding];

    [request setHTTPBody:data];

    //  4
注意!!!!!!!!新方法的不同

    //  4.1
创建会话

    NSURLSession *session = [NSURLSessionsharedSession];

    //  4.2
创建数据请求任务

    NSURLSessionDataTask *task = [session
dataTaskWithRequest:request completionHandler:^(NSData *_Nullable data,
NSURLResponse *_Nullable response,
NSError * _Nullable error) {

        NSDictionary *dic = [NSJSONSerializationJSONObjectWithData:data
options:NSJSONReadingAllowFragmentserror:nil];

        NSLog(@"%@", dic);

    }];

    //  4.3
启动任务

    [task resume];

    

}

图片的异步加载通常采用这种网络请求方式, 在封装网络请求工具类的时候,

//  从子线程回到主线程进行界面更新 (iOS中更新界面只能在主线程)

        dispatch_async(dispatch_get_main_queue(), ^{

            block(image);

        });
详见网络请求封装工具类
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息