(9.0版本以下get,post)网络编程
点击工程中“info.plist”,
添加“App Transport Security Settings”,
“Allow Arbitrary Loads--YES”
在9.0以下的版本中,此方法不可用,
NSURLConnection sendSynchronousRequest
在工程中的“Deplotment info”中,
修改“Deployment Target”为9.0以下均可
9.0以下 get请求
远程资源的地址
NSURL *url=[NSURL URLWithString:@"https://api.heweather.com/x3/citylist?search=allchina&key=48d7d68f454c4e01b3005e671c849990"];
创建请求对象
NSURLRequest *request=[NSURLRequest requestWithURL:url];
发送请求
NSURLResponse *response=nil;
JSON格式的数据
NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
解析数据
NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
_array=dic[@"city_info"];
9.0以下
post请求
NSURL *url=[NSURL URLWithString:@"https://api.heweather.com/x3/weather"];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"post"];
NSString *httpBody=[NSString stringWithFormat:@"cityid=%@&key=48d7d68f454c4e01b3005e671c849990",str];
[request setHTTPBody:[httpBody dataUsingEncoding:NSUTF8StringEncoding]];
NSURLResponse *respone=nil;
NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&respone error:nil];
NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"%@",dic);
(9.0版本以上get,post)网络编程
点击工程中“info.plist”,
添加“App Transport Security Settings”,
“Allow Arbitrary Loads--YES”
在9.0以上的版本中,此方法可用,
NSURLConnection sendSynchronousRequest
在工程中的“Deplotment info”中,
修改“Deployment Target”为9.0以上均可
9.0以上
get请求
远程资源的地址
NSURL *url = [NSURL URLWithString:@"https://api.heweather.com/x3/citylist?search=allchina&key=e1f85b8fd1ad40b2aa5b0e236f465180"];
创建请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
发送请求
NSURLResponse *response = nil;
创建一个数据传输任务
NSURLSessionDataTask *dataTask=[[NSURLSession sharedSession]dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
data服务器返回的数据、response响应、error错误
解析数据
NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
_array=dic[@"city_info"];
NSLog(@"obj--%@",_array);
[_tableView reloadData];}];
执行任务
[dataTask resume];
9.0以上
post请求
NSURL *urlI=[NSURL URLWithString:@"https://api.heweather.com/x3/citylist"];
创建Request对象
NSMutableURLRequest *requestI=[NSMutableURLRequest requestWithURL:urlI]; [requestI setHTTPMethod:@"POST"];
[requestI setHTTPBody:[[NSString stringWithFormat:@"search=%@&key=48d7d68f454c4e01b3005e671c849990",@"allchina"]dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTask *dataTaskI=[[NSURLSession sharedSession]dataTaskWithRequest:requestI completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error==nil){
NSDictionary *dicI=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
_arrayI=dicI[@"city_info"];
NSLog(@"obj--%@",dicI);
[_tableView reloadData];}
数据交换的任务
NSHTTPURLResponse *responseI=(NSHTTPURLResponse *)response;
NSLog(@"%li",responseI.statusCode);
if (responseI.statusCode==200){
NSLog(@"响应成功");
NSDictionary *dicI=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];}
else{NSLog(@"响应失败,%li",responseI.statusCode);}}];
执行任务
[dataTaskI resume];
1、同步请求可以从因特网请求数据,一旦发送同步请求,程序将停止用户交互,直至服务器返回数据完成,才可以进行下一步操作,
2、异步请求不会阻塞主线程,而会建立一个新的线程来操作,用户发出异步请求后,依然可以对UI进行操作,程序可以继续运行
3、GET请求,将参数直接写在访问路径上。操作简单,不过容易被外界看到,安全性不高,地址最多255字节;
4、POST请求,将参数放到body里面。POST请求操作相对复杂,需要将参数和地址分开,不过安全性高,参数放在body里面,不易被捕获。
5、同步和异步的区别在于连接方式不同:
同步用:
NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:Nil error:nil]; 异步用:
NSURLConnection * connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];(需要在.h中指定代理)
6、同步GET请求
第一步,创建URL
NSURL * url = [[NSURL alloc]initWithString:@"http://e.hiphotos.baidu.com/image/w%3D1366%3Bcrop%3D0%2C0%2C1366%2C768/sign=66f9b9980ef431adbcd2473a7d0097cc/08f790529822720ed8bdbef079cb0a46f21fab4d.jpg"];
第二步,通过URL创建request请求
NSURLRequest * request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
NSURLRequest初始化方法第一个参数:请求访问路径,第二个参数:缓存协议,第三个参数:网络请求超时时间(秒)
其中缓存协议是个枚举类型包含:
NSURLRequestUseProtocolCachePolicy(基础策略)
NSURLRequestReloadIgnoringLocalCacheData(忽略本地缓存)
NSURLRequestReturnCacheDataElseLoad(首先使用缓存,如果没有本地缓存,才从原地址下载)
NSURLRequestReturnCacheDataDontLoad(使用本地缓存,从不下载,如果本地没有缓存,则请求失败,此策略多用于离线操作)
NSURLRequestReloadIgnoringLocalAndRemoteCacheData(无视任何缓存策略,无论是本地的还是远程的,总是从原地址重新下载)
NSURLRequestReloadRevalidatingCacheData(如果本地缓存是有效的则不下载,其他任何情况都从原地址重新下载)
第三步,连接服务器
NSURLResponse * respones = nil;
NSError * error = nil;
NSData * reviced = [NSURLConnection sendSynchronousRequest:request returningResponse:&respones error:&error];
第四步,将数据转换成图片
UIImage * image = [[UIImage alloc]initWithData:reviced];
_imageView.image = image; 7.异步GET请求
第一步,创建URL
NSURL * url = [[NSURL alloc]initWithString:@"http://e.hiphotos.baidu.com/image/w%3D1366%3Bcrop%3D0%2C0%2C1366%2C768/sign=66f9b9980ef431adbcd2473a7d0097cc/08f790529822720ed8bdbef079cb0a46f21fab4d.jpg"];
第二步,通过URL创建request请求
NSURLRequest * request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
第三步,连接服务器
[NSURLConnection connectionWithRequest:request delegate:self];//(需要在.h中指定代理方法)
接受到服务器的回应调用
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{ [self.reviceData setLength:0 ]; }
数据传输中一直调用
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{[self.reviceData appendData:data]; }
数据传输完才会调用
(void)connectionDidFinishLoading:(NSURLConnection *)connection
{ UIImage * image = [[UIImage alloc]initWithData:self.reviceData];
_imageView.image = image; }
8、同步POST请求
第一步,创建URL
NSURL * url = [[NSURL alloc]initWithString:@"http://api.hudong.com/iphonexml.do"];
第二步,通过URL创建可变的request请求(只有创建可变的request才能设置POST请求)
NSMutableURLRequest * request1 = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:100];
timeoutInterval:post超时最大时间是240秒,在方法中设置多少秒也没用。
第三步,设置POST请求方式
[request1 setHTTPMethod:@"POST"];
第四步,设置参数
NSString * bodyStr = @"type=focus-c";
NSData * body = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
[request1 setHTTPBody:body];
第五步,连接服务器
NSData * data = [NSURLConnection sendSynchronousRequest:request1 returningResponse:nil error:nil];
NSString * str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",str);
9、异步POST请求
第一步,创建URL
NSURL * url = [[NSURL alloc]initWithString:@"http://api.hudong.com/iphonexml.do"];
第二步,通过URL创建可变的request请求(只有创建可变的request才能设置POST请求)
NSMutableURLRequest * request1 = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:100];
timeoutInterval:post超时最大时间是240秒,在方法中设置多少秒也没用。
第三步,设置POST请求方式
[request1 setHTTPMethod:@"POST"];
第四步,设置参数
NSString * bodyStr = @"type=focus-c";
NSData * body = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
[request1 setHTTPBody:body];
第五步,连接服务器
[[NSURLConnection alloc]initWithRequest:request2 delegate:self]
接受到服务器的回应调用
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{ [self.reviceData setLength:0 ]; }
数据传输中一直调用
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{ [self.reviceData appendData:data]; }
数据传输完才会调用
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{ NSString * str = [[NSString alloc]initWithData:self.reviceData encoding:NSUTF8StringEncoding];
NSLog(@"%@",str); }