美文网首页
iOS网络—请求类NSURLRequest详解

iOS网络—请求类NSURLRequest详解

作者: lionsom_lin | 来源:发表于2017-12-28 15:18 被阅读85次

    NSURLRequest
    iOS网络编程之四——请求类NSURLRequest使用详解

    一、NSURLRequest函数介绍

    ==========================================================
    ==========================类方法===========================
    ==========================================================
    /*
      通过这种方式创建的请求对象 默认使用NSURLRequestUseProtocolCachePolicy缓存逻辑 默认请求超时时限为60s
     */
    + (instancetype)requestWithURL:(NSURL *)URL;
    
    /*
      < readonly > 返回一个BOOL值 用于判断是否支持安全编码
     */
    @property (class, readonly) BOOL supportsSecureCoding;
    
    /*
      请求对象的初始化方法 创建时设置缓存逻辑和超时时限
      自定义:
        cachePolicy:
        timeoutInterval:
      */
    + (instancetype)requestWithURL:(NSURL *)URL cachePolicy:(NSURLRequestCachePolicy)cachePolicy timeoutInterval:(NSTimeInterval)timeoutInterval;
    
    ==========================================================
    =======================对象方法=============================
    ==========================================================
    /*
      init方法进行对象的创建 默认使用NSURLRequestUseProtocolCachePolicy缓存逻辑 默认请求超时时限为60s
     */
    - (instancetype)initWithURL:(NSURL *)URL;
    
    /*
      init方法进行对象的创建
     */
    - (instancetype)initWithURL:(NSURL *)URL cachePolicy:(NSURLRequestCachePolicy)cachePolicy timeoutInterval:(NSTimeInterval)timeoutInterval NS_DESIGNATED_INITIALIZER;
    
    /*
      < readonly > 只读属性 获取请求对象的URL
     */
    @property (nullable, readonly, copy) NSURL *URL;
    
    /*
      < readonly > 只读属性 缓存策略枚举
     */
    @property (readonly) NSURLRequestCachePolicy cachePolicy;
    
    /*
      < readonly > 只读属性 获取请求的超时时限
     */
    @property (readonly) NSTimeInterval timeoutInterval;
    
    /*
      < readonly > 主文档地址 这个地址用来存放缓存
     */
    @property (nullable, readonly, copy) NSURL *mainDocumentURL;
    
    /*
      < readonly > 获取网络请求的服务类型
      作用:指定网络传输类型。精切指出传输类型,可以让系统快速响应,提高传输质量,延长电池寿命等
     */
    @property (readonly) NSURLRequestNetworkServiceType networkServiceType API_AVAILABLE(macos(10.7), ios(4.0), watchos(2.0), tvos(9.0));
    
    /*
      < readonly > 获取是否允许使用服务商蜂窝网络
     */
    @property (readonly) BOOL allowsCellularAccess  API_AVAILABLE(macos(10.8), ios(6.0), watchos(2.0), tvos(9.0));
    

    拓展

    ==========================================================
    =====================缓存策略枚举===========================
    ==========================================================
    typedef NS_ENUM(NSUInteger, NSURLRequestCachePolicy)
    {
        //默认的缓存协议
        NSURLRequestUseProtocolCachePolicy = 0,
    
        //无论有无本地缓存数据 都进行从新请求
        NSURLRequestReloadIgnoringLocalCacheData = 1,
        //忽略本地和远程的缓存数据 未实现的策略
        NSURLRequestReloadIgnoringLocalAndRemoteCacheData = 4, 
        //无论有无缓存数据 都进行从新请求
        NSURLRequestReloadIgnoringCacheData = NSURLRequestReloadIgnoringLocalCacheData,
    
        //先检查缓存 如果没有缓存再进行请求
        NSURLRequestReturnCacheDataElseLoad = 2,
        //类似离线模式,只读缓存 无论有无缓存都不进行请求
        NSURLRequestReturnCacheDataDontLoad = 3,
    
        //未实现的策略
        NSURLRequestReloadRevalidatingCacheData = 5, // Unimplemented
    };
    
    
    ==========================================================
    =================网络请求的服务类型枚举=======================
    ==========================================================
    typedef NS_ENUM(NSUInteger, NSURLRequestNetworkServiceType)
    {
        // 普通网络传输,默认使用这个
        NSURLNetworkServiceTypeDefault = 0,     // Standard internet traffic
        // 网络语音通信传输,只能在VoIP使用
        NSURLNetworkServiceTypeVoIP = 1,        // Voice over IP control traffic
        // 影像传输
        NSURLNetworkServiceTypeVideo = 2,      // Video traffic
        // 网络后台传输,优先级不高时可使用。对用户不需要的网络操作可使用
        NSURLNetworkServiceTypeBackground = 3, // Background traffic
        // 语音传输
        NSURLNetworkServiceTypeVoice = 4       // Voice data
    };
    

    二、NSMutableURLRequest介绍

    NSURLRequest请求类除了在初始化时可以设定一些属性,创建出来后则大部分属性都为只读的,无法设置与修改。另一个类NSMutableURLRequest可以更加灵活的设置请求的相关属性。NSMutableURLRequest 继承 NSURLRequest。
    /*
      设置请求的URL
    */
    @property (nullable, copy) NSURL *URL;
    
    /*
      设置请求的缓存策略
    */
    @property NSURLRequestCachePolicy cachePolicy;
    
    /*
      设置超时时间
    */
    @property NSTimeInterval timeoutInterval;
    
    /*
      设置缓存目录
    */
    @property (nullable, copy) NSURL *mainDocumentURL;
    
    /*
      设置网络服务类型
     */
    @property NSURLRequestNetworkServiceType networkServiceType API_AVAILABLE(macos(10.7), ios(4.0), watchos(2.0), tvos(9.0));
    
    /*
      设置是否允许使用服务商蜂窝网
     */
    @property BOOL allowsCellularAccess API_AVAILABLE(macos(10.8), ios(6.0), watchos(2.0), tvos(9.0));
    

    三、NSURLRequest请求对象与HTTP/HTTPS协议相关请求的属性设置

    以下属性的设置必须使用NSMutableURLRequest类,如果是NSURLRequest,则只可以读,不可以修改。
    /*
      设置HPPT请求方式 默认为 “GET”
    */
    @property (copy) NSString *HTTPMethod;
    
    /*
      通过字典设置HTTP请求头的键值数据
    */
    @property (nullable, copy) NSDictionary<NSString *, NSString *> *allHTTPHeaderFields;
    
    /*
      设置http请求头中的字段值
    */
    - (void)setValue:(nullable NSString *)value forHTTPHeaderField:(NSString *)field;
    
    /*
      向http请求头中添加一个字段
    */
    - (void)addValue:(NSString *)value forHTTPHeaderField:(NSString *)field;
    
    /*
      设置http请求体 用于POST请求
    */
    @property (nullable, copy) NSData *HTTPBody;
    
    /*
      设置http请求体的输入流
    */
    @property (nullable, retain) NSInputStream *HTTPBodyStream;
    
    /*
      设置发送请求时是否发送cookie数据
    */
    @property BOOL HTTPShouldHandleCookies;
    
    /*
      设置请求时是否按顺序收发 默认禁用 在某些服务器中设为YES可以提高网络性能
     */
    @property BOOL HTTPShouldUsePipelining API_AVAILABLE(macos(10.7), ios(4.0), watchos(2.0), tvos(9.0));
    
    

    拓展 -- HTTP请求头

    关于HTTP请求头

    • Accept-Encoding

      • 表示本地可以接收压缩格式的数据,而服务器在处理时就将大文件压缩再发回客户端。客户端接收完成后在本地对数据进行解压操作。
    • Content-Type

      • 表示内容类型,一般是指客户端存在的Content-Type,用于定义网络文件的类型和网页的编码,决定客户端将以什么形式、什么编码读取这个文件。即用于标识发送或接收到的数据的类型,客户端根据该参数来决定数据的打开方式。
    • Content-Length

      • 表示述HTTP消息实体的传输长度。消息实体长度:即Entity-length,压缩之前的message-body的长度;
    • Authorization

      • HTTP基本认证是一种用来允许Web浏览器,或其他客户端程序在请求时提供以用户名和口令形式的凭证的登录方式。授权机制根据服务端定的规则确定。

    四、举个栗子

    4.1、普通的Post请求

    // 把bodyString转换为NSData数据  
    NSData *bodyData = [[bodyString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]dataUsingEncoding:NSUTF8StringEncoding];
    // 获取到服务器的url地址  
    NSURL *serverUrl = [[NSURL URLWithString:RequestUrl] URLByAppendingPathComponent:urlStr];
    
    // 请求这个地址, timeoutInterval:10 设置为10s超时:请求时间超过10s会被认为连接不上,连接超时  
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:serverUrl  
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData  
                                                       timeoutInterval:10];
    // POST请求  
    [request setHTTPMethod:@"POST"];
    // body 数据  
    [request setHTTPBody:bodyData];
    // 请求头  
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"]; 
    // 或者  --  设置请求头,用POST请求,给服务器发送JSON数据
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"111318d2-b5a5-1998-be2a-30607d1591ca" forHTTPHeaderField:@"appid"]; 
    
    // 同步发送request,成功后会得到服务器返回的数据
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];  
    

    4.2、特殊请求:NSURLRequest设置自定义请求头

    iOS开发之如何在NSURLRequest中设置自定义header请求头

     // 设置url,这里是百度API查询天气的一个接口  
        NSString *strURL =[[NSString alloc]  
                           initWithFormat:@"http://apis.baidu.com/heweather/weather/free?city=%@",  @"guangzhou"];  
          
        strURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  
          
        NSURL *url = [NSURL URLWithString:strURL];  
        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];  
      
        //添加header  
        NSMutableURLRequest *mutableRequest = [request mutableCopy];    //拷贝request  
        [mutableRequest addValue:@"你的apikey" forHTTPHeaderField:@"apikey"];  
        request = [mutableRequest copy];        //拷贝回去  
        /**********************************************/  
      
        NSLog(@"%@", request.allHTTPHeaderFields);  //打印出header验证      
        NSURLConnection *connection = [[NSURLConnection alloc]  
                                       initWithRequest:request  
                                       delegate:self];  
    

    基本上完结 !

    相关文章

      网友评论

          本文标题:iOS网络—请求类NSURLRequest详解

          本文链接:https://www.haomeiwen.com/subject/pdwmgxtx.html