• 同步/异步网络请求


    字符串转为数据:[target dataUsingEncoding:];

    数据转为字符串:[[NSString alloc]initWithData:encoding:];

    响应状态:[NSHTTPURLResponse  localizedStringForStatusCode:];

    异步post开子线程写

    1.HTTP请求方法
    GET请求
    POST请求
    这2种请求方法都要大写字母。
    2.区别
    GET:通常用于请求URL并得到资源
    POST:用于提交数据到服务器
    如GET:
    http://www.baidu.com/img/123.jpg
    http://www.baidu.com?name=123
    3.URL连接方式
    同步连接(软件安装):同步(需要等待的状态),一个人做多件事,要完成1件才可以做第2件
    异步连接(后台下载):多处理(单件事多个人做),通过代理实现
    总的来说:当请求的数据量小时,同步连接是不错的选择,缺点:UI会“冻结”。异步连接适用于大数据,UI不“冻结”。
    4.NSString、NSData、NSArray、UImage等类都有从URL初始化数据的方法,这个方法便是系统封装好的GET请求的同步连接方式。

    5.创建一个GET同步连接
    step1.创建URL对象,指定路径
    step2.创建NSURLRequest对象,设置请求方法,默认GET
    step3.创建NSURLConnect对象,发送同步连接(核心步骤
    step4.接收数据
    6.创建一个POST同步连接
    step2:创建NSMutableURLRequest对象,设置为POST连接方式
    7.GET异步连接
    step1.创建URL对象,指定路径
    step2.创建NSURLRequest对象,设置请求方法,默认GET
    step3:创建NSURLConnection对象,并设置代理,发送异步连接
    step4.代理方法中接收数据
    8.POST异步连接
    step2:创建NSMutableURLRequest对象,设置为POST连接方式


    GET同步

     // 1.创建URL对象
        NSURL * url = [NSURL URLWithString:@"http://192.168.1.5:8080/Jersey/rest/contacts"];
        // 2.创建 NSURLRequest 对象
        NSURLRequest * request = [NSURLRequest requestWithURL:url
                                                  cachePolicy:NSURLRequestReloadIgnoringCacheData // 忽略缓存
                                              timeoutInterval:10.0f];
        
        // 3.创建 NSURLConnection 对象,发送同步请求
        // 设置回应和错误的指针变量
        NSHTTPURLResponse * response = nil;
        NSError * error = nil;
        // 发起同步链接
        NSData * data = [NSURLConnection sendSynchronousRequest:request//同步会卡在这里
                                              returningResponse:&response
                                                          error:&error];
        
        
        // 4.接收数据
        // 打印回应和错误信息
        NSLog(@"response = %@",[NSHTTPURLResponse localizedStringForStatusCode:[response statusCode]]);
        NSLog(@"error = %@",[error localizedRecoveryOptions]);
        // 打印字符串信息
        NSString * str = [[NSString alloc] initWithData:data
                                               encoding:NSUTF8StringEncoding];
        
        if (response.statusCode == 200)
        {
            NSLog(@"str = %@",str);
        }
        //NSLog(@"str = %@",str);
        // 打印请求方式
        NSLog(@"request method = %@",[request HTTPMethod]);

    POST同步

      // 1
        NSURL * url2 = [NSURL URLWithString:@"http://192.168.1.5:8080/Jersey/rest/contacts/addContact"];
        // 2
        NSMutableURLRequest * req = [NSMutableURLRequest requestWithURL:url2
                                                            cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                        timeoutInterval:10.0f];
        // 3
        NSString * string = @"<contact><id>3007</id><name>Song</name></contact>";
        NSData * postData = [string dataUsingEncoding:4 allowLossyConversion:YES];
        NSString * len = [NSString stringWithFormat:@"%d",postData.length];
        // 设置请求方式
        [req setHTTPBody:postData];
        [req setHTTPMethod:@"POST"];
        [req setValue:@"application/xml" forHTTPHeaderField:@"Content-Type"];
        [req setValue:len forHTTPHeaderField:@"Content-Length"];
        // 4
        NSError * err;
        NSURLResponse * resp;
        NSData *urlData = [NSURLConnection sendSynchronousRequest:req
                                                returningResponse:&resp
                                                            error:&err];
        
        // 5
        NSString * responseStr = [[NSString alloc] initWithData:urlData
                                                       encoding:NSUTF8StringEncoding];
        
        NSLog(@"request method = %@",[req HTTPMethod]);
        NSLog(@"len = %@",len);
        NSLog(@"responseStr = %@",responseStr);

     异步

    AppDelegate.h

    #import <UIKit/UIKit.h>
    
    @interface AppDelegate : UIResponder <UIApplicationDelegate,NSURLConnectionDataDelegate>
    {
        NSMutableData *_mData;
    }
    @property (strong, nonatomic) UIWindow *window;
    
    @end

    AppDelegate.m

    GET异步

    NSString *str = @"http://192.168.1.5:8080/Jersey/rest/contacts";
        //1
        NSURL *url = [NSURL URLWithString:str];
        NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0f];
        //
        [NSURLConnection connectionWithRequest:request delegate:self];

    POST异步

    NSString *str = @"http://192.168.1.5:8080/Jersey/rest/contacts/addContact";
        NSURL *url = [NSURL URLWithString:str];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10.0f];
        //
        NSString *string = @"<contact><id>3007</id><name>Song</name></contact>";
        
        NSData *postData = [string dataUsingEncoding:4
                                allowLossyConversion:YES];//api上说没法识别时,是否支持转换为同一编码,也就是否允许失真
        
        NSString *len = [NSString stringWithFormat:@"%d",postData.length];//内容的字节长度
        
        
        [request setValue:@"application/xml" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:postData];
        [request setHTTPMethod:@"POST"];
        
        
        [NSURLConnection connectionWithRequest:request delegate:self];//?该返回值有什么用,为什么不用[NSURLConnection sendAsynchronousRequest:];
        
        NSLog(@"request method = %@",[request HTTPMethod]);
        NSLog(@"len = %@",len);

    重写代理方法,系统自动调用

    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {
        NSLog(@"%s",__func__);//服务器响应就会执行这个方法
        _mData = [[NSMutableData alloc]init];
    }
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    {
        NSLog(@"%s",__func__);//当开始接受到数据的时候,数据量大的时候执行多次
        [_mData appendData:data];//将多个数据添加到可变data中
        //算进度
    }
    
    -(void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
        NSLog(@"%s",__func__);//数据接受完后
        NSString *str = [[NSString alloc]initWithData:_mData encoding:4];
        NSLog(@"str = %@",str);
    }
    -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
    {
        NSLog(@"%s",__func__);//连接接受失败
    }

    //文件读写
        //写文件
        NSString *path1 = @"/Users/yf02/Desktop/Oc_12/123.txt";
        
        
        NSString *content = @"i am a ios developer";
        
        NSError *error = nil;
        BOOL s = [content writeToFile:path1//写到的位置,默认覆盖,没追加
                           atomically:YES//Yes 先写到缓存,再从缓存写入文件
                             encoding:NSUTF8StringEncoding
                                error:&error];//指针的指针,有2个返回值
        if (!s)
        {
            NSLog(@"error:%@",[error localizedFailureReason]);
            exit(-1);
        }
        
        //读文件(url可以是网络路径[NSURL URLWithString:],也可以本地路径)
        NSURL *url = [NSURL fileURLWithPath:path1];
        NSString *u = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
        NSLog(@"%@",u);
        
        
        
        //NSData主要存二进制数据(系统常用二进制文件)
        NSData *data = [NSData dataWithContentsOfFile:path1];
        NSLog(@"%@",data);
        NSString *dataCoutent = [[NSString alloc]initWithData:data encoding:4];
        NSLog(@"%@",dataCoutent);
        //
        [data writeToFile:path1 atomically:YES];//不用编码,比字符串更安全更快速
        
        
        
        //NSFileManger对目录操作(单例)
        NSFileManager *fm = [NSFileManager defaultManager];
        [fm createDirectoryAtPath:@"/Users/yf02/Desktop/Oc_12/abc/123"
      withIntermediateDirectories:YES//中间目录
                       attributes:nil//nil默认为可以读可写
                            error:nil];
        
        [fm createFileAtPath:@"/Users/yf02/Desktop/Oc_12/abc/123/helloworld.txt"
                    contents:data
                  attributes:nil];
        
        [fm moveItemAtPath:@"/Users/yf02/Desktop/Oc_12/abc/123/helloworld.txt"
                    toPath:@"/Users/yf02/Desktop/Oc_12/abc/helloworld.txt"
                     error:nil];
        
        
        
        //包(单例)
        NSBundle *mainBundle = [NSBundle mainBundle];
        NSString *mainBundlePath = [mainBundle pathForResource:@"helloworld" ofType:@"txt"];//要先关联好文件
        NSLog(@"mainBundlePath:%@",mainBundlePath);
        NSString *BundleContent= [NSString stringWithContentsOfFile:mainBundlePath encoding:4 error:nil];
        NSLog(@"BundleContent = %@",BundleContent);
        //NSBundle不能写入内容
        NSString *string1 = @"abc";
        BOOL return1 = [string1 writeToFile:mainBundlePath
                                 atomically:YES
                                   encoding:4
                                      error:nil];
        NSLog(@"return1 = %d",return1);
  • 相关阅读:
    TortoiseSVN 实现文件的移动
    CSS选择器
    聚合报告90%参数说明
    JMeter响应断言详解
    测试结果分析
    Selenium+TestNG+Java报错:org.testng.internal.ObjectFactoryImpl.newInstance(ObjectFactoryImpl.java:40)
    在IntelliJ IDEA通过Maven添加依赖无效
    CentOS下安装TestLink
    Mysql存储过程生成指定格式的订单号
    Mysql使用函数生成指定随机字段内容
  • 原文地址:https://www.cnblogs.com/huen/p/3546475.html
Copyright © 2020-2023  润新知