首页 > 代码库 > NSUrlConnection 和 NSUrlRequest 的关系

NSUrlConnection 和 NSUrlRequest 的关系

开始看到这2个名字,总感觉NSUrlConnection才是主要的网络请求类,其实不是,先看官方文档

An NSURLConnection object lets you load the contents of a URL by providing a URL request object. The interface for NSURLConnection is sparse, providing only the controls to start and cancel asynchronous loads of a URL request. You perform most of your configuration on the URL request object itself.Note: Although instances of this class are commonly called “connections”, there is not a 1:1 correlation between these objects and the underlying network connections.

如上所说,这里的connection,并不是只真正的网络连接,它仅仅负责开始和取消网络请求,并且会负责分发网络回调方法。

而NSURLRequest对象才是真正的网络设置类,一般利用NSMutableURLRequest类,它的主要方法如下:

setURL:setHTTPMethod:setTimeoutInterval:- (void)addValue:(NSString *)value forHTTPHeaderField:(NSString *)field- (void)setHTTPBody:(NSData *)data