iOS Network

本文详细介绍了iOS中的网络请求实现方式,包括GET与POST的区别及应用,缓存策略的应用,以及同步与异步请求的具体实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



@interface ViewController () <NSURLConnectionDataDelegate, NSURLConnectionDelegate>


// 用于接受数据的可变data

@property (nonatomic,strong) NSMutableData *receiveData;



@end



@implementation ViewController



// 接收到网络回应后执行

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

{

    // 接收到网络回应之后,开辟一个可变data空间,用于接受数据

    NSLog(@"%@", @"接收到网络回应");

    self.receiveData = [NSMutableData data];

    

    

}



// 接收到服务器传递的数据就执行

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

{

    // 接受服务器传递过来的数据,并且拼接数据

    [self.receiveData appendData:data];

    

    NSLog(@"正在接受数据");

    

}


// 数据接受完成之后执行

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    NSLog(@"数据请求完成,开始解析");

    

    NSDictionary *rootDic = [NSJSONSerialization JSONObjectWithData:self.receiveData options:0 error:nil];

    

    NSLog(@"%@", rootDic);

    

    

}




// 连接失败执行

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

{

    NSLog(@"%@", error);

}


- (void)viewDidLoad {

    [super viewDidLoad];


    // 1 . 了解常用的网络协议、 C/S 模式,主要了解 http https 协议

    // 2.  掌握如何处理Xcode7.0 之后的 http 请求。

    // 3.  重点掌握 iOShttp请求。掌握请求的步骤。

    

    

    // iOS 网络请求的对象及其作用

    // 1. NSURL  网址对象,存储要请求地址的网址

    // 2. NSURLRequest 请求对象,根据网址发起网络请求

    // 3. NSURLConnection 链接对象,请求成功后,建立链接,传输数据

    

 

    

    // request 网络请求

    // 网络请求有两种方式 一种是 get 一种是post

    // get请求方式, 明文传输数据,通过url传输,最大255字节

    // post 请求方式, data包传输数据, 通过NSData,二进制包传输, 最大可以1G

    

    // get 请求,通常用于不需要加密的数据,传输效率高

    // post 请求, 通常用于需要加密的数据,比如:用户登录注册页面, 安全性高

    

    

    // iOS 网络请求的步骤 四步

    // 1. 建立网络地址对象 nsurl

    // 2. 创建网络请求对象 nsurlrequest 设置请求方式

    // 3. 使用网络连接对象,请求数据 ,同步请求或者异步请求

    // 4. 解析数据

    

    

    

    

    // Xcode7.0 之后默认只支持https 安全超文本传播协议

    // 如果想要往前做兼容 则需要修改info.plist 文件

    // 添加以下字段

    /*

     <key>NSAppTransportSecurity</key>

     

     <dict>

     

     <key>NSAllowsArbitraryLoads</key>

     

     <true/>

     

     </dict>

     */

    

    

    


    // Do any additional setup after loading the view, typically from a nib.

}


#pragma mark-

#pragma mark 缓存策略


- (IBAction)cachePolicy:(id)sender {

    

    // 1. url

    NSURL *url = [NSURL URLWithString:@"http://bea.wufazhuce.com/OneForWeb/one/getC_N?strDate=2015-11-18&strRow=4&strMS=1"];

    

    // 2. 创建可变request 对象。

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:15];

    

    // 参数2 缓存策略

    // 参数3 最长请求时间,如果超出时间,没有与服务器建立连接,则认为请求失败

    

    // 3. 判断有无缓存响应

    // 创建一个缓存区

    NSURLCache *cache = [NSURLCache sharedURLCache];

    

    // 设置缓存区大小

    [cache setMemoryCapacity:4 * 1024 * 1024]; // 4M

    

    // 获取缓存响应

    NSCachedURLResponse *cacheResponse = [cache cachedResponseForRequest:request];

    

    // 如果缓存区存在内容,则取得非空的缓存相应,设置request 缓存策略模式为离线模式

    if (cacheResponse != nil) {

        

        //

        NSLog(@"存在缓存内容,使用离线模式");

        // 不加载新数据,使用离线数据

        [request setCachePolicy:(NSURLRequestReturnCacheDataDontLoad)];

    }

    

    // 4. connection 同步请求方式

    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    

    

    // 5. json解析

    NSDictionary *rootDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

    

    NSDictionary *contentEntity = [rootDic objectForKey:@"contentEntity"];

    

    NSString *sGW = [contentEntity objectForKey:@"sGW"];

    

    NSLog(@"%@", sGW);

    

}



// post 同步请求

- (IBAction)postSync:(id)sender {

    

    // post  请求与 get 不同

    // post 请求,请求参数 服务器路径分开设置, get则是都在url 网址里存放。

    // 因此 post 只能只用 NSMutableRequest 可变请求对象。

    

    // http://bea.wufazhuce.com/OneForWeb/one/getC_N?strDate=2015-11-18&strRow=1&strMS=1

    

    // 服务器路径 http://bea.wufazhuce.com/OneForWeb/one/getC_N

    // 请求sql字符串(传递的参数) strDate=2015-11-18&strRow=1&strMS=1

    

    

    // 1. 创建nsurl对象

    NSURL *url = [NSURL URLWithString:@"http://bea.wufazhuce.com/OneForWeb/one/getC_N"]; // 注意: post 请求中,url不包含传递参数,而是在 request中单独设置

    

    

    // 2. 创建 NSMutableURLRequest 对象

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

    

    //  设置请求类型 POST 请求

    [request setHTTPMethod:@"POST"];

    

    //  设置请求参数 url 问号后面的参数

    [request setHTTPBody:[@"strDate=2015-11-18&strRow=1&strMS=1" dataUsingEncoding:NSUTF8StringEncoding]];

    

    // 3. connection 同步请求方式

    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    

    

    // 4. json解析

    NSDictionary *rootDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

    

    NSDictionary *contentEntity = [rootDic objectForKey:@"contentEntity"];

    

    NSString *sGW = [contentEntity objectForKey:@"sGW"];

    

    NSLog(@"%@", sGW);


}



// post 异步请求

- (IBAction)postAsync:(id)sender {

    

    // 1. 创建nsurl对象

    NSURL *url = [NSURL URLWithString:@"http://bea.wufazhuce.com/OneForWeb/one/getC_N"]; // 注意: post 请求中,url不包含传递参数,而是在 request中单独设置

    

    

    // 2. 创建 NSMutableURLRequest 对象

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

    

    //  设置请求类型 POST 请求

    [request setHTTPMethod:@"POST"];

    

    //  设置请求参数 url 问号后面的参数

    [request setHTTPBody:[@"strDate=2015-11-18&strRow=1&strMS=1" dataUsingEncoding:NSUTF8StringEncoding]];

    

//    [NSURLConnection connectionWithRequest:request delegate:self];


    

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

        NSDictionary *rootDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

        

        NSDictionary *contentEntity = [rootDic objectForKey:@"contentEntity"];

        

        NSString *string = [contentEntity objectForKey:@"sGW"];

        

        NSLog(@"%@,hehe", string);

    }];

    

    

    

    

}











// get同步请求

- (IBAction)getSync:(id)sender {

    

    // 1. 创建URL地址对象

    NSURL *url = [NSURL URLWithString:@"http://bea.wufazhuce.com/OneForWeb/one/getC_N?strDate=2015-11-18&strRow=1&strMS=1"]; // string就是我们的网址

    

    // 2. NSURLRequest 创建请求对象,

    // 请求对象分两种,一个不可变的,用于 get请求,一种可变的NSMutableURLRequest ,用于post请求

    // 只有可变请求对象,可以再次设置缓存协议。

    

    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; // 不可变的请求对象,为get请求方式,url里面包含请求参数

    

    // 3. 使用网络链接请求数据 NSURLConnection

    // 网络链接请求数据,分为两种方式,同步请求方式,和异步请求方式。

    // 区别: 同步会卡线程, 异步不会。

    NSData *data =  [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    

    // 4. json 解析

    NSDictionary *rootDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

    // contentEntity

    NSDictionary *contentEntity = [rootDic objectForKey:@"contentEntity"];

    

    // sGW

    NSString *sGW = [contentEntity objectForKey:@"sGW"];

    

    NSLog(@"%@",sGW);

    

}



// get异步请求

- (IBAction)getAsync:(id)sender {

    

    // 1. url

    NSURL *url = [NSURL URLWithString:@"http://bea.wufazhuce.com/OneForWeb/one/getC_N?strDate=2015-11-18&strRow=1&strMS=1"];

    

    // 2. request

    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

    

    

    // 3. connection  使用代理方式,进行异步请求

    [NSURLConnection connectionWithRequest:request delegate:self];

    

    

    

    

    

    /*

    // 3. connection 异步请求

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

        

        // block在这里作为方法参数,起着回调作用。

        // 当代码执行到此block之后,单独又开辟了一个线程去执行网络请求,当网络请求完成后,执行此block,把请求到的data数据,通过该block参数 data。传递给我们

        

        NSDictionary *rootDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

        

        NSDictionary *contentEntity = [rootDic objectForKey:@"contentEntity"];

        

        NSString *string = [contentEntity objectForKey:@"sGW"];

        

        NSLog(@"%@", string);

        

    }];

     

     */

    

    

    

    

}


@end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值