iOS 网络编程 (三)NSURLConnection使用

来源:互联网 发布:nginx反向代理设置 编辑:程序博客网 时间:2024/06/06 19:33

1 常用类

  1. NSURL:请求地址
  2. NSURLRequest:一个NSURLRequest对象就代表一个请求,包含的信息有:
    一个NSURL对象;
    请求方法、请求头、请求体
    请求超时
  3. NSMutableURLRequest:NSURLRequest的子类
  4. NSURLConnection:负责发送请求,建立客户端和服务器的连接。
发送NSURLRequest的数据给服务器,并收集来自服务器的响应数据。

NSURLConnection的使用步骤
使用NSURLConnection发送请求的步骤很简单:
1 创建一个NSURL对象,设置请求路径。
2 传入NSURL创建一个NSURLRequest对象,设置请求头和请求体。
3 使用NSURLConnection发送NSURLRequest



2 NSURLConnection发送请求


NSURLConnection常见的发送请求方法有以下几种:
1 同步请求
+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error;
2 异步请求 :根据对服务器返回数据对处理方式对不同,又可分为2种
block回调
+ (void)sendAsynchronousRequest:(NSURLRequest*) request                          queue:(NSOperationQueue*) queue                                                  completionHandler:(void (^)(NSURLResponse* response, NSData* data, NSError* connectionError)) handler;
代理
//类方法+ (nullable NSURLConnection*)connectionWithRequest:(NSURLRequest *)request delegate:(nullable id)delegate;//实例方法- (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开始发送请求。
使用代理时需要成为NSURLConnection的代理,最好遵守NSURLConnectionDataDelegate协议。

NSURLConnection这几个发送请求的方法,在iOS9.0已经弃用了。

3 NSURLConnectionDelegate

NSURLConnectionDelegate协议中的代理方法
//开始接收到服务器的响应时调用- (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
NSMutalbURLRequest 是NSURLRequest的子类,常用方法有:
//设置请求超时等待时间(超过这个时间就算超时,请求失败)- (void)setTimeoutInterval:(NSTimeInterval)seconds;//设置请求方法(比如GET和POST)- (void)setHTTPMethod:(NSString *)method;//设置请求体- (void)setHTTPBody:(NSData *)data;//设置请求头- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field;

4 GET 请求

三种get请求。
/** * 发送同步请求  get */- (void)syncGetRequest{    NSLog(@"syncRequest sendSynchronousRequest");    // 0.请求路径    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it"];    //    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/video"];    //NSURL *url = [NSURL URLWithString:@"http:www.baidu.com"];    // 1.创建请求对象    NSURLRequest *request = [NSURLRequest requestWithURL:url];        // 2.发送请求    // sendSynchronousRequest阻塞式的方法,等待服务器返回数据    NSHTTPURLResponse *response = nil;    NSError *error = nil;        NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];        // 3.解析服务器返回的数据(解析成字符串)    NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];    NSLog(@"%@ %@", string, response.allHeaderFields);}/** * 发送异步请求  get */- (void)asyncGetRequest{    NSLog(@"async sendAsynchronousRequest");    // 0.请求路径    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it"];    // 1.创建请求对象    NSURLRequest *request = [NSURLRequest requestWithURL:url];        // 2.发送请求    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {        // 请求完毕会来到这个block        // 3.解析服务器返回的数据(解析成字符串)        NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];        NSLog(@"sendAsynchronousRequest %@", string);        //        NSHTTPURLResponse *r = (NSHTTPURLResponse *)response;        //        //        NSLog(@"%zd %@", r.statusCode, r.allHeaderFields);    }];    NSLog(@"async sendAsynchronousRequest end");}- (void)delegateAysncGetRequest{    NSLog(@"delegateAysnc ");    // 0.请求路径    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it"];        // 1.创建请求对象    NSURLRequest *request = [NSURLRequest requestWithURL:url];        // 2.创建连接对象    //    [[NSURLConnection alloc] initWithRequest:request delegate:self];        //    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];    //    [conn start];    // 取消    //    [conn cancel];    [NSURLConnection connectionWithRequest:request delegate:self];}

5 POST请求

发送post请求和get请求的发送方式差不多,只是请求路径和请求对象不一样。
Post请求的URL不需要携带参数,参数设置在请求体中。
-(void)asyncPostRequest{    // 1.请求路径    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"];    // 2.创建请求    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];    // 更改请求方法 默认为GET    request.HTTPMethod = @"POST";    // 设置请求体    request.HTTPBody = [@"username=520it&pwd=520it" dataUsingEncoding:NSUTF8StringEncoding];    // 设置超时(5秒后超时)    request.timeoutInterval = 5;    // 设置请求头    [request setValue:@"iOS 9.0" forHTTPHeaderField:@"User-Agent"];        // 3.发送请求    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {        if (connectionError) { // 比如请求超时 没连网络            NSLog(@"----请求失败");        } else {            NSLog(@"------%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);        }    }];}

6 中文处理

当URL中有中文时处理方法:
// 0.请求路径    NSString *urlStr = @"http://120.25.226.186:32812/login2?username=小码哥&pwd=520it";    // 将中文URL进行转码    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];    NSURL *url = [NSURL URLWithString:urlStr];
后面的处理和正常情况一样。

当参数中有中文时类似。转换编码格式。
request.HTTPBody = [@"username=小码哥&pwd=520it" dataUsingEncoding:NSUTF8StringEncoding];

下载地址


0 0
原创粉丝点击