常用类
- NSURL:请求地址
- NSURLRequest:一个NSURLRequest对象就代表一个请求,它包含的信息有
一个NSURL对象
请求方法、请求头、请求体
请求超时… …
- NSMutableURLRequest:NSURLRequest的子类
- NSURLConnection
- 负责发送请求,建立客户端和服务器的连接
- 发送数据给服务器,并收集来自服务器的响应数据
NSURLConnection的使用步骤
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;
代理
- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate;
+ (NSURLConnection*)connectionWithRequest:(NSURLRequest *)request delegate:(id)delegate;
- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately;
在startImmediately = NO的情况下,需要调用start方法开始发送请求
- (void)start;
成为NSURLConnection的代理,最好遵守NSURLConnectionDataDelegate协议
NSURLConnectionDelegate
NSURLConnectionDataDelegate协议中的代理方法
开始接收到服务器的响应时调用
- (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;
NSMutableURLRequest
NSMutableURLRequest是NSURLRequest的子类,常用方法有
设置请求超时等待时间(超过这个时间就算超时,请求失败)
- (void)setTimeoutInterval:(NSTimeInterval)seconds;
设置请求方法(比如GET和POST)
- (void)setHTTPMethod:(NSString *)method;
设置请求体
- (void)setHTTPBody:(NSData *)data;
设置请求头
- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field;
创建GET和POST请求
// 创建GET请求
NSString *urlStr = [@"http://120.25.226.186:32812/login2?username=小码哥&pwd=520it" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 创建POST请求
NSString *urlStr = @"http://120.25.226.186:32812/login";
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
// 请求体
NSString *bodyStr = @"username=520it&pwd=520it";
request.HTTPBody = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
多值参数
- 有时候一个参数名,可能会对应多个值
http://120.25.226.186:32812/weather?place=Beijing&place=Henan&place=Hunan
- 服务器的place属性是一个数组