GET同步请求
NSString *strURL = @"http://api.map.baidu.com/place/v2/search?query=银行®ion=大连&output=json&ak=6E823f587c95f0148c19993539b99295";
一个正常的URL地址是不允许有中文的,只能有数字和26个英文字母的大小写.和一些特殊符号比如& %等,如果遇到带中文的URL,首先把它进行编码
把汉字变成编码
NSString *strEncode = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
URL符合要求之后,就开始进行网络请求,网络请求分为三步
(1).根据已经编码好的URL,创建一个NSURL
NSURL *url = [NSURL URLWithString:strEncode];
(2).发送一个请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
(3).返回我们要的数据,一个NSData对象
第一个参数:刚刚创建的请求
第二个参数:返回的一个响应
第三个参数:错误信息
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
对返回回来的数据,data进行json解析
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
打印所有银行的名字
for (NSDictionary *temp in dic[@"results"]) {
NSLog(@"%@", temp[@"name"]);
}
如果请求不下来数据会发生崩溃 崩溃信息为 Data is nil
------------------------------------------------------------------------------------------------------------------------------------------------
POST同步请求
NSString *strURL = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
当前的网址找不到任何数据, 但是可以知道数据在哪
前两步和之前的GET请求一样
NSURL *url = [NSURL URLWithString:strURL];
NSMutableURLRequest *request= [NSMutableURLRequest requestWithURL:url];
接下来是POST请求独有的部分
把请求的方式首先设置成POST,默认是GET
[request setHTTPMethod:@"POST"];
接下来需要把请求的内容放到request的body中
NSString *bodyStr = @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";
需要把请求部分的字符串变成NSData类型的对象
NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
把bodyData放到request中
[request setHTTPBody:bodyData];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
json解析
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"%@", dic);
------------------------------------------------------------------------------------------------------------------------------------------------
GET异步请求
缓冲图片
NSString *strURL=@"http://img4.duitang.com/uploads/item/201207/28/20120728105310_jvAjW.thumb.600_0.jpeg";
NSURL *url = [NSURL URLWithString:strURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
前两步还是和之前一样
第三步出现变化,通过代理的方式进行异步操作 (签订协议)<NSURLConnectionDataDelegate>
[NSURLConnection connectionWithRequest:request delegate:self];
协议方法1
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
只要接收到服务器放回的响应信息,就会走这个方法,我们在这个方法里需要对接收数据的容器data进行初始化的设置
self.data = [NSMutableData data];
}
协议方法2
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
只要返回数据,就会走这个协议方法
把返回的数据累加到容器里
appendData是累加的意思
[self.data appendData:data];
}
协议方法3
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
等到整个请求已经结束,需要吧返回的data对imageView进行添加
self.imageView.image = [UIImage imageWithData:self.data];
}
同步和异步GET请求在步骤上完全相同, 只是在第三步同步使用的是sendSyn的方法,异步使用的是代理的方法,异步是基于同步进行操作
------------------------------------------------------------------------------------------------------------------------------------------------
POST异步请求
NSString *strURL = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
1.创建URL
NSURL *url = [NSURL URLWithString:strURL];
2.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
3.设置request的请求方式
[request setHTTPMethod:@"POST"];
4.
NSString *bodyStr = @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";
5.bodyStr -> NSData
NSData *data = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
6.把bodyData添加到requst里面
[request setHTTPBody:data];
7.网络请求在子线程里进行请求,请求下来的数据需要通过控件作为载体显示出来,需要把数据在主线程里显示,第二个参数就指定把数据放回哪个线程
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
参数的data就是我们请求下来的数据,接下来数据的额解析就在block中进行
NSLog(@"%@", data);
json解析
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
for (NSDictionary *temp in dic[@"news"]) {
NSLog(@"%@", temp);
}
}];
------------------------------------------------------------------------------------------------------------------------------------------------
GET异步请求通过block的方式
NSString *str = @"http://img4.duitang.com/uploads/item/201207/28/20120728105310_jvAjW.thumb.600_0.jpeg";
1.创建一个nsurl
NSURL *url = [NSURL URLWithString:str];
2.发送一个请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
3.异步
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
数据处理依旧在block中进行
self.imageView.image = [UIImage imageWithData:data];
}];
总结
网络请求的步骤:
(1).根据网址的字符串,创建一个NSURL对象
(2).根据这个url对象,创建一个请求
(3).发送请求,然后获取请求对象.同步和异步的区别就是在请求的方法选用有差别,其他都一样
POST就是比GET请求多一个需要给request添加一个body
----------------------------------------------------------------------------------------------------------------------------------------------
NSString *path = [[NSBundle mainBundle]pathForResource:@"movielist" ofType:@"txt"];
NSData *data = [NSData dataWithContentsOfFile:path];
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
for (NSDictionary *temp in dic[@"result"]) {
movieData *movie = [[movieData alloc]init];
[movie setValuesForKeysWithDictionary:temp];
[self.movieArr addObject:movie];
[movie release];
-------------- ---------------------- ---------------------- -------------------------------------------------- 解析网络数据NSString *strURL = @"http://project.lanou3g.com/teacher/yihuiyun/lanouproject/movielist.php";
NSURL *url = [NSURL URLWithString:strURL];
NSMutableURLRequest *requst = [NSMutableURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:requst queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
for (NSDictionary *temp in dic[@"result"]) {
movieData *movie = [[movieData alloc]init];
[movie setValuesForKeysWithDictionary:temp];
[self.movieArr addObject:movie];
[movie release];
}
[self.movieTableView reloadData];
self.hud.hidden = YES;
}];
self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
self.hud.labelText = @"请稍后";