Single View Application
ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
ViewController.m
#import "ViewController.h"
@interface ViewController ()<NSURLConnectionDataDelegate>
- (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;
@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(110, 400, 150, 150)];
self.imageView.backgroundColor = [UIColor cyanColor];
[self.view addSubview:self.imageView];
[_imageView release];
// NSUserDefaults
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)synGET:(id)sender {
// 同步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. 建立一个连接
// NSURLSession 网络请求 自己看
// 参数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:0 error:nil];
NSLog(@"**同步get**%@", dic);
// NSLog(@"%@", response);
}
- (IBAction)synPOST:(id)sender {
// post请求需要在请求的过程里, 添加一个body, 添加之后才可以获取数据
NSString *urlStr = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
// 1. 创建一个URL
NSURL *url = [NSURL URLWithString:urlStr];
// 2. 创建一个请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 指定请求的方式, 默认是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(@"**同步post**%@", dic);
// NSArray *firstArr = dic[@"news"];
// for (NSDictionary *tempDic in firstArr) {
// NSLog(@"!~!%@", tempDic[@"summary"]);
// }
}
- (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];
// 连接
// 这个方法可以在2.0到9.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 {
// 这个方法会接收返回的数据
// append是累加的意思
[self.data appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
self.imageView.image = [UIImage imageWithData:self.data];
}
- (IBAction)asynPOST:(id)sender {
// 异步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];
// 设置请求的方式
[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(@"**异步post**%@", dic);
}];
}
- (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(@"**异步getBlock**%@", dic);
}];
}
@end
#pragma mark 总结: 常用的请求方式有两种, 一个是GET, 一个是POST, 它俩本质上没有任何区别, 只是POST在请求的时候需要添加一个body, 同步和异步: 都是用异步的方式进行加载, 加载过程中还可以操作其他的功能, 不会出现卡死的情况, 从同步演化出异步, 请求分为三步: 1. 创建URL, 2. 创建请求request, 3. 建立连接, 完成数据请求, iOS9.0之后, NSURLConnection用的越来越局限, NSURLSession未来更重要