前面我们学习过了多线程的诸多知识,现在该学习网络,学习网络少不了的是发送网络请求,跟服务器进行交互。在iOS中,发送网络请求可以使用NSURLConnection类
这没什么好说的,我们可以将字符串变成URL,也可以直接设置URL,例如:
//这里对字符串进行的处理是因为URL里面不支持中文,而进行的百分号变换,将中文变成百分号格式NSString *urlStr = [@"http://120.25.226.186:32812/login?username=123&pwd=123" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];NSURL *url = [NSURL URLWithString:urlStr];
可以直接设置请求对象,用NSURLRequest,但是这样不能对请求进行更细致的设置
NSURLRequest *request = [NSURLRequest requestWithURL:url];
要进行更细致的设置,如请求方式,请求头等的设置,只能使用NSURLRequest的子类NSMutableURLRequest:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];request.HTTPMethod = @"POST";// 请求体NSString *bodyStr = @"username=123&pwd=123";request.HTTPBody = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
我们一共可以设置的请求属性如下表示:
设置请求超时等待时间(超过这个时间就算超时,请求失败)- (void)setTimeoutInterval:(NSTimeInterval)seconds;设置请求方法(比如GET和POST)- (void)setHTTPMethod:(NSString *)method;设置请求体- (void)setHTTPBody:(NSData *)data;设置请求头- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field;
+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error;
参数:
特点:
根据对服务器返回数据的处理方式的不同,又可以分为2种
1、block回调方式的异步
+ (void)sendAsynchronousRequest:(NSURLRequest*) request queue:(NSOperationQueue*) queue completionHandler:(void (^)(NSURLResponse* response, NSData* data, NSError* connectionError)) handler;
2、代理的方式异步
- (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协议
开始接收到服务器的响应时调用- (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;
创建GET请求NSString *urlStr = [@"http://120.25.226.186:32812/login?username=123&pwd=123" 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=123&pwd=123";request.HTTPBody = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
例如:
NSString *urlStr = @"http://120.25.226.186:32812/login2?username=小黄人&pwd=520it&type=JSON";urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];NSURL *url = [NSURL URLWithString:urlStr];
新闻热点
疑难解答