iOS网络之NSURLRequest API介绍
关于NSURLRequest基本的用法这里不再讨论,相信都了解,我们直接看看它的API,还是喜欢从API入手了解一个类。
当然,我们也不用每一个属性那样去解释,有些的确是太简单了,直接从感觉需要我们梳理一下的地方入手,具体的每一个属性建议大家自己去看看头文件了解。
下面说的点对着这NSURLRequest头文件更容易理解:
/*! @method requestWithURL:cachePolicy:timeoutInterval: @abstract Allocates and initializes a NSURLRequest with the given URL and cache policy. @param URL The URL for the request. @param cachePolicy The cache policy for the request. @param timeoutInterval The timeout interval for the request. See the commentary for the <tt>timeoutInterval</tt> for more information on timeout intervals. @result A newly-created and autoreleased NSURLRequest instance. 这个是类方法的初始化方法,参数就是缓存策略和超时时间 这里引入了这个NSURLRequestCachePolicy缓存策略的枚举类型,下面梳理这个枚举。 typedef NS_ENUM(NSUInteger, NSURLRequestCachePolicy) { 默认缓存策略 NSURLRequestUseProtocolCachePolicy = 0, URL应该加载源端数据,不使用本地缓存数据 NSURLRequestReloadIgnoringLocalCacheData = 1, 本地缓存数据、代理和其他中介都要忽视他们的缓存,直接加载源数据 NSURLRequestReloadIgnoringLocalAndRemoteCacheData = 4, // Unimplemented 从服务端加载数据,完全忽略缓存。和NSURLRequestReloadIgnoringLocalCacheData一样 NSURLRequestReloadIgnoringCacheData = NSURLRequestReloadIgnoringLocalCacheData, 使用缓存数据,忽略其过期时间;只有在没有缓存版本的时候才从源端加载数据 NSURLRequestReturnCacheDataElseLoad = 2, 只使用cache数据,如果不存在cache,就请求失败,不再去请求数据 用于没有建立网络连接离线模式 NSURLRequestReturnCacheDataDontLoad = 3, 指定如果已存的缓存数据被提供它的源段确认为有效则允许使用缓存数据响应请求,否则从源段加载数据。 NSURLRequestReloadRevalidatingCacheData = 5, // Unimplemented }; */
+ (instancetype)requestWithURL:(NSURL *)URL cachePolicy:(NSURLRequestCachePolicy)cachePolicy timeoutInterval:(NSTimeInterval)timeoutInterval;
我们再接着往下看:
这里说一下NS_DESIGNATED_INITIALIZER 和 NS_UNAVAILABLE 这两个宏,这两个宏相信你要是经常看头文件的话是很容易碰到的。
/*! @abstract Returns the cache policy of the receiver. @result The cache policy of the receiver. 缓存策略 */
@property (readonly) NSURLRequestCachePolicy cachePolicy; /*! @abstract Returns the timeout interval of the receiver. @discussion The timeout interval specifies the limit on the idle interval alloted to a request in the process of loading. The "idle interval" is defined as the period of time that has passed since the last instance of load activity occurred for a request that is in the process of loading. Hence, when an instance of load activity occurs (e.g. bytes are received from the network for a request), the idle interval for a request is reset to 0. If the idle interval ever becomes greater than or equal to the timeout interval, the request is considered to have timed out. This timeout interval is measured in seconds. @result The timeout interval of the receiver. 请求超时时间 */ @property (readonly) NSTimeInterval timeoutInterval; /*! @abstract The main document URL associated with this load. @discussion This URL is used for the cookie "same domain as main document" policy. There may also be other future uses. See setMainDocumentURL: NOTE: In the current implementation, this value is unused by the framework. A fully functional version of this method will be available in the future. @result The main document URL. 主文档地址 这个地址用来存放缓存 */
@property (nullable, readonly, copy) NSURL *mainDocumentURL; /*! @abstract Returns the NSURLRequestNetworkServiceType associated with this request. @discussion This will return NSURLNetworkServiceTypeDefault for requests that have not explicitly set a networkServiceType (using the setNetworkServiceType method). @result The NSURLRequestNetworkServiceType associated with this request. 获取网络请求的服务类型 枚举如下 */
@property (readonly) NSURLRequestNetworkServiceType networkServiceType API_AVAILABLE(macos(10.7), ios(4.0), watchos(2.0), tvos(9.0)); /*! @abstract returns whether a connection created with this request is allowed to use the built in cellular radios (if present). @result YES if the receiver is allowed to use the built in cellular radios to satify the request, NO otherwise. 获取是否允许使用服务商蜂窝网络 */
@property (readonly) BOOL allowsCellularAccess API_AVAILABLE(macos(10.8), ios(6.0), watchos(2.0), tvos(9.0));
NSURLRequest还有一个NSHTTPURLRequest的类别,这个类别对于我们自定义请求头请求体这些的时候是很重要的,我们先看看这个类别里面有什么:
/*! HTTP请求方式 POST GET 等 */ @property (nullable, readonly, copy) NSString *HTTPMethod; /*! 得到一个字典数据,设置的 HTTP请求头的键值数据 */ @property (nullable, readonly, copy) NSDictionary<NSString *, NSString *> *allHTTPHeaderFields; /*! 设置http请求头中的字段值,这个我们待会在看看一些Demo代码和AF的源码比较一下 */ - (nullable NSString *)valueForHTTPHeaderField:(NSString *)field; /*! 请求体 */ @property (nullable, readonly, copy) NSData *HTTPBody; /*! http请求体的输入流 */ @property (nullable, readonly, retain) NSInputStream *HTTPBodyStream; /*! 设置发送请求时是否发送cookie数据 */ @property (readonly) BOOL HTTPShouldHandleCookies; /*! 设置的请求时是否按顺序收发 默认禁用 在某些服务器中设为YES可以提高网络性能 */ @property (readonly) BOOL HTTPShouldUsePipelining API_AVAILABLE(macos(10.7), ios(4.0), watchos(2.0), tvos(9.0)); /*! 设置http请求头中的字段值 */ - (void)setValue:(nullable NSString *)value forHTTPHeaderField:(NSString *)field; /*! 向http请求头中添加一个字段 */ - (void)addValue:(NSString *)value forHTTPHeaderField:(NSString *)field;
可以看到这个类别全都是关于请求体和请求头的一些设置方法以及属性,既然这里我们说到了这两个东西,我们也说说,下面是我们常见的请求头设置属性:
Host: 目标服务器的网络地址 Accept: 让服务端知道客户端所能接收的数据类型,如text/html Content-Type: body中的数据类型,如application/json; charset=UTF-8 Accept-Language: 客户端的语言环境,如zh-cn Accept-Encoding: 客户端支持的数据压缩格式,如gzip User-Agent: 客户端的软件环境,我们可以更改该字段为自己客户端的名字,比如QQ music v1.11,比如浏览器Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/600.8.9 (KHTML, like Gecko) Maxthon/4.5.2 Connection: keep-alive,该字段是从HTTP 1.1才开始有的,用来告诉服务端这是一个持久连接,“请服务端不要在发出响应后立即断开TCP连接”。关于该字段的更多解释将在后面的HTTP版本简介中展开。 Content-Length: body的长度,如果body为空则该字段值为0。该字段一般在POST请求中才会有。