Write the code,Change the world。

iOS开发使用NSURLConnection、NSURLSession、AFN、ASI四种方式实现HTTP请求

 

概括:HTTP请求可以使用NSURLConnection、NSURLSession、AFN、ASI等方式实现,其中又包括了get、post两种请求方式和同步、异步两种程序执行方式。

 

NSURLConnection


1 get方式的同步请求

/**

 *  get同步请求

 */

-(void) getSynch{

    // 获取URL

    NSURL *url = [[NSURL alloc] initWithString:@"http://localhost:8070/MJServer/login?username=123&password=123"];

    // 获取request请求

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    

    

    // 发送同步请求

    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    

    // 将data转换成string

    NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    

    NSLog(@"data -- %@", result);

}

 


2 get方式的异步请求 

/**

 *  get异步请求

 */

-(void) getAsynch{

    // 获取URL

    NSURL *url = [[NSURL alloc] initWithString:@"http://localhost:8070/MJServer/video"];

    // 获取request请求

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    

    // 发送同步请求

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

        

        // 将data数据转成字典

        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];

        NSLog(@"data -- %@", dict);

    }];

}

 


3 post同步请求 

/**

 *  post同步请求

 */

-(void) postSynch{

    // 获取URL

    NSURL *url = [[NSURL alloc] initWithString:@"http://localhost:8070/MJServer"];

    

    // 设置post请求需要使用NSMutableURLRequest

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    // 设置请求方式为post (必选)

    request.HTTPMethod = @"POST";

 

    // 发送同步请求

    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    

    // 将data转换成string

    NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    

    NSLog(@"data -- %@", result);

    

}

 


4 post异步请求 

/**

 *  post异步请求

 */

-(void) postAsynch{

    // 获取URL

    NSURL *url = [[NSURL alloc] initWithString:@"http://localhost:8070/MJServer/login"];

    // 获取request请求

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    // 设置请求方式为post

    request.HTTPMethod = @"POST";

    

    // 设置表单参数 (可选)

    NSString *params = [NSString stringWithFormat:@"username=123&pwd=123"];

    request.HTTPBody = [params dataUsingEncoding:NSUTF8StringEncoding];

    

    // 设置超时(可选)

    request.timeoutInterval = 5;

    

    // 设置请求头信息(可选)

    [request setValue:@"iPhone 6" forHTTPHeaderField:@"User-Agent"];

    

    // 设置post请求需要使用NSMutableURLRequest

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

        

        // 将data数据转成字典

        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];

        NSLog(@"data -- %@", dict);

    }];

}

 


NSURLSession 


1 session的get请求

/**

 *  session的get请求

 */

-(void) sessionGet{

    // 获取一个session实例

    NSURLSession *session = [NSURLSession sharedSession];

    

    // 获取url

    NSURL *url = [[NSURL alloc] initWithString:@"http://localhost:8070/MJServer/video"];

    // 创建一个数据访问任务

    NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        NSLog(@"data -- %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);

    }];

    // 启动任务,开始、回复都用resume

    [task resume];

}

 


2 session的post请求 

/**

 *  session的post请求

 */

-(void) sessionPost{

    // 获取一个session实例

    NSURLSession *session = [NSURLSession sharedSession];

    

    // 获取url

    NSURL *url = [[NSURL alloc] initWithString:@"http://localhost:8070/MJServer/login"];

    // 获取request请求对象

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    // 设置请求方式

    request.HTTPMethod = @"POST";

    // 设置请求体,

    NSString *params = @"username=123&pwd=123";

    request.HTTPBody = [params dataUsingEncoding:NSUTF8StringEncoding];

    

    // 创建一个数据访问任务

    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        NSLog(@"data -- %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);

    }];

    

    // 开始任务

    [task resume];

}

 


AFNetwork框架,需要导入 #import "AFNetworking.h"  


1 AFN的get请求

 #import "AFNetworking.h" 

/**

 *  afn的get请求

 */

-(void) afnGet{

    // 创建一个请求操作管理者

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

 

    // 声明响应结果不进行json、xml等格式解析,直接返回data

    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    

    // 设置请求参数(可选)

    NSMutableDictionary *params = [NSMutableDictionary dictionary];

    params[@"username"] = @"123";

    params[@"pwd"] = @"123";

    

    

    // 发送get请求

    NSString *url = @"http://localhost:8070/MJServer/login";

    [manager GET:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {

        // 请求成功在这里处理

        // 将响应数据转换成字典

        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];

        NSLog(@"%@", dict);

    

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        // 如果请求失败在这里处理

        NSLog(@"request fail");

    }];

}

 


2 AFN的post请求 

/**

 *  afn的post请求

 */

-(void) afnPost{

    // 创建一个请求操作管理者

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    

    // 声明响应结果不进行json、xml等格式解析,直接返回data

    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    

    // 设置请求参数(可选)

    NSMutableDictionary *params = [NSMutableDictionary dictionary];

    params[@"username"] = @"123";

    params[@"pwd"] = @"123";

    

    

    // 发送get请求

    NSString *url = @"http://localhost:8070/MJServer/login";

    [manager POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {

        // 请求成功在这里处理

        // 将响应数据转换成字典

        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];

        NSLog(@"%@", dict);

        

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        // 如果请求失败在这里处理

        NSLog(@"request fail");

    }];

}

 


ASI(注意添加libz类库并修改ASI源文件为非arc) 


1 ASI的get同步请求

 #import "ASIHTTPRequest.h" 

/**

 *  ASI的get同步请求

 */

-(void) asiGetSynch{

    // 获取url

    NSURL *url = [[NSURL alloc] initWithString:@"http://localhost:8070/MJServer/video"];

    

    // 获取asi请求对象

    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];

    // 发送同步请求

    [request startSynchronous];

    

    NSError *error = [request error];

    if (error) {

        NSLog(@"请求失败");

    }else{

//        NSString *data = [request responseString];

        NSData *data = [request responseData];

        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];

        NSLog(@"result -- %@", result);

    }

}

 


2 ASI的get异步请求 

/**

 *  ASI的get异步请求

 *  须知:ASI监听请求过程有delegate、block和selector三种方式,

 *  经测试发现,delegate和block可以同时执行,selector和block也可以同时执行,但delegate和selector共存时(包括三者共存)不执行delegate

 *  执行顺序:delegate > selector > block

 *  通过responseData和responseString获取不到数据

 *  使用了代理就不能直接通过responseData和responseString获取到数据

 */

-(void) asiGetAsynch{

    // 获取url

    NSURL *url = [[NSURL alloc] initWithString:@"http://localhost:8070/MJServer/video"];

    

    // 获取asi请求对象

    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];

    

    // 设置ASIHTTPRequestDelegate代理。

    request.delegate = self;

    

    // 发送异步请求

    [request startAsynchronous];

 

    // 设置监听请求过程的block

    [request setStartedBlock:^{

        NSLog(@"block请求开始");

    }];

    

    [request setDataReceivedBlock:^(NSData *data) {

        NSLog(@"block获得请求数据 -- %@", [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]);

    }];

 

    [request setCompletionBlock:^{

        NSLog(@"block请求结束");

    }];

    

    // 设置监听请求过程的selector

    [request setDidStartSelector:@selector(start:)];

    [request setDidReceiveDataSelector:@selector(receiveData:)];

    [request setDidFinishSelector:@selector(finish:)];

 

}

 

#pragma mark selector监听方法

-(void)start:(ASIHTTPRequest *)request{

    NSLog(@"selector请求开始");

}

 

-(void) receiveData:(ASIHTTPRequest *) request{

    // 这里获取不到数据

    NSLog(@"selector获得请求数据 -- %@", [request responseString]);

}

 

 

-(void)finish:(ASIHTTPRequest *)request{

    NSLog(@"selector请求结束");

}

 

#pragma mark 实现ASIHTTPRequestDelegate的代理方法

- (void)request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data{

 

    NSLog(@"delegate获得请求数据 -- %@", [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]);

}

 

- (void)requestStarted:(ASIHTTPRequest *)request{

    

    NSLog(@"delegate请求开始");

}

 

- (void)requestFinished:(ASIHTTPRequest *)request{

    NSLog(@"delegate请求结束");

}

 

- (void)requestFailed:(ASIHTTPRequest *)request{

    NSLog(@"delegate请求失败");

}

 


3 ASI的post异步请求 

 #import "ASIFormDataRequest.h" 

/**

 *  ASI的post异步请求

 */

-(void) asiPostAsynch{

    

    // 获取url

    NSURL *url = [[NSURL alloc] initWithString:@"http://localhost:8070/MJServer/login"];

    

    // 获取ASI表单请求对象

    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];

    

    // 设置请求参数

    [request setPostValue:@"123" forKey:@"username"];

    [request setPostValue:@"123" forKey:@"pwd"];

    

    // 使用了代理就不能直接通过responseData和responseString获取数据

//    request.delegate = self;

    

    // 发送异步请求

    [request startAsynchronous];

    

    // 设置监听(这里只演示block方法)

    __weak ASIFormDataRequest *req = request;

    [request setCompletionBlock:^{

        NSLog(@"selector获得请求数据 -- %@", [req responseString]);

    }];

}

 

posted @ 2014-10-03 23:22  JQTech  阅读(2377)  评论(1编辑  收藏  举报

页脚Html代码