码迷,mamicode.com
首页 > Web开发 > 详细

NSURLConnection

时间:2015-07-13 00:45:29      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

NSURLConnection的GET请求:

  - 发送同步请求

    // 0.请求路径
    NSURL *url = [NSURL URLWithString:@"http://XXX.XXX.XXX.XXX:32812/login?username=123&pwd=345"];
   
    // 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);

 

  - 发送异步请求

    // 0.请求路径
    NSURL *url = [NSURL URLWithString:@"http://XXX.XXX.XXX.XXX:32812/login?username=123t&pwd=123"];
    
    // 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(@"%@", string);
        //        NSHTTPURLResponse *r = (NSHTTPURLResponse *)response;
        //
        //        NSLog(@"%zd %@", r.statusCode, r.allHeaderFields);
    }];

  

  - 代理方式<NSURLConnectionDataDelegate>

- (void)delegateAysnc
{
    // 0.请求路径
    NSURL *url = [NSURL URLWithString:@"http://XXX.XXX.XXX.XXX:32812/login?username=122&pwd=123"];
    
    // 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];
    
    [NSURLConnection connectionWithRequest:request delegate:self];
    
    // 取消
//    [conn cancel];
}

#pragma mark - <NSURLConnectionDataDelegate> -- being
/**
 * 接收到服务器的响应
 */
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // 创建data对象
    self.responseData = [NSMutableData data];
    NSLog(@"didReceiveResponse");
}

/**
 * 接收到服务器的数据(如果数据量比较大,这个方法会被调用多次)
 */
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // 不断拼接服务器返回的数据
    [self.responseData appendData:data];
    NSLog(@"didReceiveData -- %zd", data.length);
}

/**
 * 服务器的数据成功接收完毕
 */
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"connectionDidFinishLoading");
    NSString *string = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
    NSLog(@"%@", string);
    
    self.responseData = nil;
}

/**
 * 请求失败(比如请求超时)
 */
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"didFailWithError -- %@", error);
}
#pragma mark - <NSURLConnectionDataDelegate> -- end

 

  - POST请求

 1.请求路径
    NSURL *url = [NSURL URLWithString:@"http://XXX.XXX.XXX.XXX:32812/login"];
    
    // 2.创建请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // 更改请求方法
    request.HTTPMethod = @"POST";
    // 设置请求体
    request.HTTPBody = [@"username=123&pwd=123" 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]);
        }
    }];

 

- 总结下带中文的GET和POST

- (void)post
{
    // 0.请求路径
    NSString *urlStr = @"http://XXX.XXX.XXX.XXX:32812/login2";
    NSURL *url = [NSURL URLWithString:urlStr];
    
    // 1.创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    request.HTTPBody = [@"username=POST请求&pwd=123" dataUsingEncoding:NSUTF8StringEncoding];
    
    // 2.发送请求
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        // 3.解析服务器返回的数据(解析成字符串)
        NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@", string);
    }];
}

- (void)get
{
    // 0.请求路径
    NSString *urlStr = @"http://XXX.XXX.XXX.XXX:32812/login2?username=GET请求&pwd=123";
    // 将中文URL进行转码
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlStr];
    
    // 1.创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    // 2.发送请求
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        // 3.解析服务器返回的数据(解析成字符串)
        NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@", string);
    }];
}

 

NSURLConnection

标签:

原文地址:http://www.cnblogs.com/samyangldora/p/4641801.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!