iOS网络请求总结、GET、POST、同步、异步代码块、异步代理、第三方AFNetWorking2.0使用

论坛 期权论坛 脚本     
匿名技术用户   2020-12-22 10:36   32   0

iOS网络请求总结、GET、POST、同步、异步代码块、异步代理、第三方AFNetWorking2.0使用

首先需要明白,

GET跟POST 区别:

GET请求,将参数直接写在访问路径上。操作简单,不过容易被外界看到,安全性不高,地址最多255字节;
POST请求,将参数放到body里面。POST请求操作相对复杂,需要将参数和地址分开,不过安全性高,参数放在body里面,不易被捕获

同步 跟 异步区别:

同步请求可以从因特网请求数据,一旦发送同步请求,程序将停止用户交互,直至服务器返回数据完成,才可以进行下一步操作,

异步请求不会阻塞主线程,而会建立一个新的线程来操作,用户发出异步请求后,依然可以对UI进行操作,程序可以继续运行


以下分别介绍几种方式的使用:

1.GET 同步请求

//创建请求路径

NSString *strURL = [NSStringstringWithFormat:@"http://192.168.10.252/upload/mapi/index.php?act=register&r_type=1&email=%@&password=%@&user_name=%@",@"123456@qq.com",@"123456",@"zhangsan"];

//通过url创建网络请求

NSURLRequest *request = [NSURLRequestrequestWithURL:[NSURLURLWithString:strURL]];

NSError *error =nil;

//同步方式连接服务器

NSData *data = [NSURLConnectionsendSynchronousRequest:request returningResponse:nilerror:&error];

//json 解析返回数据

NSDictionary *dic = [NSJSONSerializationJSONObjectWithData:data options:kNilOptionserror:nil];

NSLog(@"%@",[dicobjectForKey:@"info"]);


2.post 同步请求

//通过url创建网络请求

NSString *strURL = [NSStringstringWithFormat:@"http://192.168.10.252/upload/mapi/index.php?"];

//通过url创建网络请求

NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:[NSURLURLWithString:strURL]];

//设置请求方式也POST(默认是GET

[request setHTTPMethod:@"POST"];

//设置请求参数

NSString *body = [NSStringstringWithFormat:@"act=%@&r_type=%d&email=%@&password=%@&user_name=%@",@"register",1,@"12345@qq.com",@"123456",@"lisi"];

//需要NSUTF8StringEncoding转码

[request setHTTPBody:[bodydataUsingEncoding:NSUTF8StringEncoding]];

//同步方式连接服务器

NSData *data = [NSURLConnectionsendSynchronousRequest:request returningResponse:nilerror:nil];

//json 解析返回数据

NSDictionary *dic = [NSJSONSerializationJSONObjectWithData:data options:kNilOptionserror:nil];

NSLog(@"%@",[dicobjectForKey:@"info"]);


3.GET 异步代码块请求

NSString *strURL = [NSString stringWithFormat:@"http://192.168.10.252/upload/mapi/index.php?act=register&r_type=1&email=%@&password=%@&user_name=%@",@"123456@qq.com",@"123456",@"zhangsan"];

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:strURL]];

NSError *error = nil;

NSLog(@"111==%@",[NSThread currentThread]);

//创建异步代码方式

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

NSLog(@"222==%@",[NSThread currentThread]);

//网络请求结束

NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

NSLog(@"%@",[dic objectForKey:@"info"]);

//回到主线程,去刷新界面

// self performSelectorOnMainThread:<#(SEL)#> withObject:<#(id)#> waitUntilDone:<#(BOOL)#>

dispatch_async(dispatch_get_main_queue(), ^{

//回主线程要做的事情

});

}];

4.POST 异步代码块请求

NSString *strURL = [NSStringstringWithFormat:@"http://192.168.10.252/upload/mapi/index.php?"];

NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:[NSURLURLWithString:strURL]];

[request setHTTPMethod:@"POST"];

[request setTimeoutInterval:10];

NSString *body = [NSStringstringWithFormat:@"act=%@&r_type=%d&email=%@&password=%@&user_name=%@",@"register",1,@"12345@qq.com",@"123456",@"lisi"];

[request setHTTPBody:[bodydataUsingEncoding:NSUTF8StringEncoding]];


[NSURLConnectionsendAsynchronousRequest:request queue:[NSOperationQueuemainQueue] completionHandler:^(NSURLResponse *response,NSData *data, NSError *connectionError) {

NSDictionary *dic = [NSJSONSerializationJSONObjectWithData:data options:kNilOptionserror:nil];

NSLog(@"%@",[dicobjectForKey:@"info"]);

}];


5. 异步代理请求

用代理需要导入协议:NSURLConnectionDataDelegate

@interface ViewController ()<NSURLConnectionDataDelegate>

NSString *strURL = [NSString stringWithFormat:@"http://192.168.10.252/upload/mapi/index.php?"];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strURL]];

[request setHTTPMethod:@"POST"];

NSString *body = [NSString stringWithFormat:@"act=%@&r_type=%d&email=%@&password=%@&user_name=%@",@"register",1,@"12345@qq.com",@"123456",@"lisi"];

[request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];

//使用代理的方式做网络请求

[NSURLConnection connectionWithRequest:request delegate:self];


#pragma mark -- 网络请求代理方法实现

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;

{

NSLog(@"网络请求总数据量,这个只执行一次");

infoData = [[NSMutableData alloc]init];

}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

NSLog(@"这个方法会执行多次!");

[infoData appendData:data];

}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection

{

NSLog(@"网络请求结束!!!");

NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:infoData options:kNilOptions error:nil];

NSLog(@"%@",dict);

NSLog(@"%@",dict[@"info"]);

}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{

NSLog(@"网络请求失败。失败原因%@",error);

}


5. 使用第三方做网络请求,AFNetWorking2.0

头文件导入:

#import "AFNetworking.h"

/*

AFNetWorking2.0 post 出现code=-1016错误怎么解决?

2.0 的你可以修改他的一个文件就可以做到了。AFURLResponseSerialization.m 这个文件找到这句话self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil]; 然后把 text/html 加进去就可以了!

*/

AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc]init];

//设置请求超时

manager.requestSerializer.timeoutInterval = 10;

//请求参数配置

NSDictionary *dict = @{@"act":@"register",@"r_type":@1,@"email":@"111222@qq.com",@"password":@"111111",@"user_name":@"wangwu1"};

// manager POST:nil parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

// //传文件的时候,会使用到这里

// } success:^(AFHTTPRequestOperation *operation, id responseObject) {

// <#code#>

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

// <#code#>

// }

[manager POST:@"http://192.168.10.252/upload/mapi/index.php?" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {

//网络请求成功了

NSLog(@"11====%@",responseObject);

NSDictionary *dic = responseObject;

NSLog(@"%@",[dic objectForKey:@"info"]);

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

//网络请求失败了。

NSLog(@"error == %@",error);

}];



如有错误!欢迎指出。。谢谢!

每天进步一点点,做一个快乐的程序猿!!

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP