一、NSURLConnection
NSURLConnection常见的发送请求方法有以下几种
- 同步请求
+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error;
- 异步请求:根据对服务器返回数据的处理方式的不同,又可以分为2种
- block回调
+ (void)sendAsynchronousRequest:(NSURLRequest*) request queue:(NSOperationQueue*) queue completionHandler:(void (^)(NSURLResponse* response, NSData* data, NSError* connectionError)) handler;
- 代理
成为NSURLConnection的代理,需要遵守NSURLConnectionDataDelegate
协议
NSURLConnectionDataDelegate协议中的代理方法- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate; + (NSURLConnection*)connectionWithRequest:(NSURLRequest *)request delegate:(id)delegate; //在startImmediately = NO的情况下,需要调用start方法开始发送请求 - (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately;
// 开始接收到服务器的响应时调用 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response; //接收到服务器返回的数据时调用(服务器返回的数据比较大时会调用多次) - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data; //服务器返回的数据完全接收完毕后调用 - (void)connectionDidFinishLoading:(NSURLConnection *)connection; //请求出错时调用(比如请求超时) - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
- block回调
NSMutableURLRequest是NSURLRequest的子类,常用方法有
//设置请求超时等待时间(超过这个时间就算超时,请求失败)
- (void)setTimeoutInterval:(NSTimeInterval)seconds;
//设置请求方法(比如GET和POST)
- (void)setHTTPMethod:(NSString *)method;
//设置请求体
- (void)setHTTPBody:(NSData *)data;
//设置请求头
- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field;
网友评论