ViewController.m
#import "ViewController.h"
#import "MBProgressHUD.h"
@interface ViewController ()<NSURLConnectionDataDelegate,MBProgressHUDDelegate>
- (IBAction)synGET:(id)sender;
- (IBAction)synPOST:(id)sender;
- (IBAction)asynGET:(id)sender;
- (IBAction)asynPOST:(id)sender;
- (IBAction)asynGETBlock:(id)sender;
@property(nonatomic, retain)NSMutableData *data;
@property(nonatomic, retain)UIImageView *imageView;
@property(nonatomic, retain)MBProgressHUD *hud;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 400, 150, 150)];
self.imageView.backgroundColor = [UIColor cyanColor];
[self.view addSubview:self.imageView];
[_imageView release];
1.创建刷新效果图
self.hud = [[MBProgressHUD showHUDAddedTo:self.view animated:YES] retain];
self.hud.delegate = self;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
2.GET同步请求
- (IBAction)synGET:(id)sender {
#pragma mark 同步GET请求.
NSString *strURL = @"http://api.map.baidu.com/place/v2/search?query=银行®ion=大连&output=json&ak=6E823f587c95f0148c19993539b99295";
// 因为网址里面不允许有汉字,只能有26个字母的大小写,数字和一些特定的符号,比如$,%,/等,所以有中文的网址要先把中文变成相对应的数字编码.
// 时间戳.
NSString *strURLEncode = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// 1.创建一个URL
NSURL *url = [NSURL URLWithString:strURLEncode];
// 2.发送一个请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 3.建立一个连接.
// 参数1:把创建好的请求发送.
// 参数2:返回的响应信息.
// 参数3:错误信息.
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data =[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
// 把data进行json解析
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"%@", dic);
NSLog(@"%@", response);
}
3.POST同步请求.
- (IBAction)synPOST:(id)sender {
#pragma mark post请求需要在请求的过程里,添加一个body,添加之后才可以获取数据.
NSString *urlStr = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
1.创建一个URL
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
2.指定请求的方式,默认是get请求
[request setHTTPMethod:@"POST"];
// body的字符串
NSString *bodyStr = @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";
// body的字符串变成NSData
NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
// 把bodyData放到request中
[request setHTTPBody:bodyData];
3.建立连接
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// json解析
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"%@", dic);
NSLog(@"******************************************************************");
// NSMutableArray *arr = [NSMutableArray array];
// arr = dic[@"news"];
for (NSMutableDictionary *temp in dic[@"news"]) {
NSLog(@"%@", temp[@"summary"]);
}
}
4.GET异步请求.
- (IBAction)asynGET:(id)sender {
NSString *strURL = @"http://img4.duitang.com/uploads/item/201207/28/20120728105310_jvAjW.thumb.600_0.jpeg";
1.创建URL.
NSURL *url = [NSURL URLWithString:strURL];
2.请求.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
3.连接.
// 这个方法只能在2.0~9.0之间的版本使用.
[NSURLConnection connectionWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// 这个方法会返回相应信息.
// 初始化装数据的容器.
self.data = [NSMutableData data];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// 这个方法会接受返回的数据.
[self.data appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
self.imageView.image = [UIImage imageWithData:self.data];
}
5.POST异步请求
- (IBAction)asynPOST:(id)sender {
#pragma mark 异步POST请求数据.
NSString *strURL = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
NSURL *url = [NSURL URLWithString:strURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 设置请求方式
[request setHTTPMethod:@"POST"];
// body的字符串
NSString *bodyStr = @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";
// body转换成NSData
NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
// 把bodyData添加到请求里
[request setHTTPBody:bodyData];
// 建立连接
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// data就是请求下来的数据.
// block里进行数据的解析.
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"%@", dic);
}];
}
6.GETBlock异步请求
- (IBAction)asynGETBlock:(id)sender {
NSString *strURL = @"http://project.lanou3g.com/teacher/yihuiyun/lanouproject/movielist.php";
NSURL *url = [NSURL URLWithString:strURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"%@", dic);
}];
}
@end
#pragma mark 总结:常用的请求方式有两种,一个GET,一个是POST,它俩本质上没有任何区别,只是POST在请求的时候需要添加一个body,同步和异步:都是用异步的方式进行加载,加载过程中还可以操作其他的功能,不会出现卡死的情况,从同步演化出异步,请求分为三步:1.创建URL,2.创建请求request,3.建立连接,完成数据请求,iOS9.0之后,NSURLConnection用的越来越局限,NSURLSession未来更重要
UI_GET&POST请求
最新推荐文章于 2023-11-10 21:00:00 发布