NSURLConnection的Get\Post方法

习惯了用AFNetworking来处理网络请求,这次试试苹果源生控件的处理方式~~

 

#import "ViewController.h"

@interface ViewController () <NSURLConnectionDataDelegate>
@property (nonatomic, strong) NSMutableData *data;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupView];
}

- (void)setupView
{
    [self connection];
}

- (void)connection
{
    NSString *urlStr = [NSString stringWithFormat:@"这里存放所需要的url"];
    
    //进行转码,以免中文乱码
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *url = [NSURL URLWithString:urlStr];
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    //设置请求超时时间
    request.timeoutInterval = 10.0;
    
    [self sendAsyncOnBlock:request];
}

//发送get请求,用block回调
- (void)sendAsyncOnBlock:(NSMutableURLRequest *)request
{
    NSOperationQueue *queue = [NSOperationQueue mainQueue];
    
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        //注意,这里回调block的线程,我是设置为主线程的。因为往往,在这里面,需要更新UI界面,而在iOS开发中,
        //更新UI界面必须在主线程中更新~~
        //
        //然后,解析json
        
        if (data){  //请求成功
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];   //解析数据
            
        }
        else{  //请求失败
            //返回的json数据为空
        }
    }];
}


//使用代理方式,发送get请求
- (void)sendAsyncOnDelegate:(NSMutableURLRequest *)request
{
    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
    [connection start];
}

//发送post请求
- (void)sendPostReq
{
    NSString *urlStr = [NSString stringWithFormat:@"这里存放所需要的url"];
    
    //进行转码,以免中文乱码
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *url = [NSURL URLWithString:urlStr];
    
    //设置为post请求
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];  //默认是get请求
    request.HTTPMethod = @"POST";
    request.timeoutInterval = 10.0;
    
    //通过请求头,告知服务器,客户端的类型
    [request setValue:@"ios" forHTTPHeaderField:@"User-Agent"];
    
    //设置请求体:(必须要设置,没有具体数据,不做示范)
//    NSString *param = [NSString stringWithFormat:];  
//    request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];
    
    //发送请求
    NSOperationQueue *queue = [NSOperationQueue mainQueue];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
    }];
}

#pragma mark -- NSURLConnectionDataDelegate

//当接受到服务器的响应(连通了服务器)就会调用
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    self.data = [[NSMutableData alloc] init];
}

//请求错误(失败)的时候调用(请求超时\断网\没有网, 一般指客户端错误)
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    
}

//当接受到服务器的数据就会调用(可能会被调用多次, 每次调用只会传递部分数据)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    //在这里,当下载大文件资源时,是需要拼接数据的
    [self.data appendData:data];
}

//当服务器的数据接受完毕后就会调用
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    
}
@end

 

你可能感兴趣的:(urlconnection)