//首先创建一个UIViewController,然后在.m文件中写入
//签订协议
@interface MainViewController ()<NSURLConnectionDataDelegate>
//可变的数据属性,用来拼接每一小块数据
@property (nonatomic,retain)NSMutableData *data;
@property (nonatomic,retain)UIImageView *imageView;
@end
@implementation MainViewController
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view.
self.imageView = [[UIImageViewalloc] initWithFrame:CGRectMake(30,64, 280, 200)];
self.imageView.backgroundColor = [UIColorredColor];
[self.viewaddSubview:self.imageView];
[_imageView release];
UIButton *buttonGET = [UIButtonbuttonWithType:UIButtonTypeSystem];
buttonGET.frame =CGRectMake(50,300, 100, 40);
buttonGET.backgroundColor = [UIColorcyanColor];
[buttonGET setTitle:@"GET请求"forState:UIControlStateNormal];
[buttonGET addTarget:selfaction:@selector(getAction:)forControlEvents:UIControlEventTouchUpInside];
[self.viewaddSubview:buttonGET];
UIButton *buttonPOST = [UIButtonbuttonWithType:UIButtonTypeSystem];
buttonPOST.frame =CGRectMake(200,300, 100, 40);
buttonPOST.backgroundColor = [UIColorcyanColor];
[buttonPOST setTitle:@"POST请求"forState:UIControlStateNormal];
[buttonPOST addTarget:selfaction:@selector(postAction:)forControlEvents:UIControlEventTouchUpInside];
[self.viewaddSubview:buttonPOST];
UIButton *buttonSync = [UIButtonbuttonWithType:UIButtonTypeSystem];
buttonSync.frame =CGRectMake(50,400, 100, 40);
buttonSync.backgroundColor = [UIColorcyanColor];
[buttonSync setTitle:@"异步连接(代理)"forState:UIControlStateNormal];
[buttonSync addTarget:selfaction:@selector(syncAction:)forControlEvents:UIControlEventTouchUpInside];
[self.viewaddSubview:buttonSync];
UIButton *buttonAsync = [UIButtonbuttonWithType:UIButtonTypeSystem];
buttonAsync.frame =CGRectMake(200,400, 100, 40);
buttonAsync.backgroundColor = [UIColorcyanColor];
[buttonAsync setTitle:@"异步连接(blick)"forState:UIControlStateNormal];
[buttonAsync addTarget:selfaction:@selector(asynAction:)forControlEvents:UIControlEventTouchUpInside];
[self.viewaddSubview:buttonAsync];
}
- (void)getAction:(UIButton *)button
{
//get请求
//1.创建请求
//地址字符串
NSString *str =@"添加网址";
//对地址进行编码处理,对一些特殊字符转为utf-8编码格式
str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//通过字符串产生一个url
NSURL *url = [NSURLURLWithString:str];
//参数1:URL
//参数2:请求数据的缓存策略
//参数3:超时时间
NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:60];
//设置请求方式(GET)
request.HTTPMethod =@"GET";
//2.建立连接,连接服务器
//同步连接服务器
//这个同步的方法可以直接获取到完整的网络数据
NSURLResponse *response = nil;
NSError *error = nil;
//参数1:要发送给服务器的请求
//参数2:从服务器获得的响应信息
//参数3:错误信息
NSData *data = [NSURLConnectionsendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(@"服务器响应信息: %@", response);
NSLog(@"错误信息: %@", error);
//3.获取数据,处理
UIImage *image = [UIImageimageWithData:data];
self.imageView.image = image;
}
- (void)postAction:(UIButton *)button
{
//post请求
//1.创建请求
NSString *str =@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURLURLWithString:str];
NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:60];
//设置请求方式
request.HTTPMethod =@"POST";
//设置post请求body
NSString *bodyStr =@"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";
//将一个字符串对象,转换为一个NSData对象
NSData *bodyData = [bodyStrdataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = bodyData;
//2.建立连接,连接服务器
NSURLResponse *response = nil;
NSError *error = nil;
NSData *resultData = [NSURLConnectionsendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(@"%@", response);
//3.处理数据
NSError *errorJSON = nil;
id result = [NSJSONSerializationJSONObjectWithData:resultData options:NSJSONReadingMutableContainerserror:&errorJSON];
NSLog(@"%@", result);
NSString *resultstr = [[NSStringalloc] initWithData:resultDataencoding:NSUTF8StringEncoding];
NSLog(@"%@", resultstr);
}
- (void)syncAction:(UIButton *)button
{
//异步连接服务器(协议方式连接)
//1.创建请求
NSString *str =@"http://api.douban.com/v2/movie/nowplaying?app_name=doubanmovie&client=e:iPhone4,1|y:iPhoneOS_6.1|s:mobile|f:doubanmovie_2|v:3.3.1|m:PP_market|udid:aa1b815b8a4d1e961347304e74b9f9593d95e1c5&alt=json&version=2&start=0&city=北京&apikey=0df993c66c0c636e29ecbb5344252a4a";
str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURLURLWithString:str];
NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:60];
request.HTTPMethod =@"GET";
//2.连接服务器
[NSURLConnectionconnectionWithRequest:request delegate:self];
}
//收到服务器的响应信息
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//每次收到服务器响应信息的时候,对数据进行初始化, 准备拼接
self.data = [NSMutableDatadata];
NSLog(@"%@", response);
}
//接收到服务器数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
//拼接数据
[self.dataappendData:data];
NSLog(@"获取数据");
}
//完成加载
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//使用数据
id resulet = [NSJSONSerializationJSONObjectWithData:self.dataoptions:NSJSONReadingMutableContainerserror:nil];
NSLog(@"完成加载");
}
- (void)asynAction:(UIButton *)button
{
//异步连接(block)
//1.创建请求
NSString *str =@"http://api.douban.com/v2/movie/nowplaying?app_name=doubanmovie&client=e:iPhone4,1|y:iPhoneOS_6.1|s:mobile|f:doubanmovie_2|v:3.3.1|m:PP_market|udid:aa1b815b8a4d1e961347304e74b9f9593d95e1c5&alt=json&version=2&start=0&city=北京&apikey=0df993c66c0c636e29ecbb5344252a4a";
str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURLURLWithString:str];
NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:60];
request.HTTPMethod =@"GET";
//2.连接服务器
//参数1:请求
//参数2:操作队列,网络请求完毕, 返回到哪个线程中
//参数3:处理数据的block
[NSURLConnectionsendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response,NSData *data, NSError *connectionError) {
//3.处理数据
NSError *resultError = nil;
id result = [NSJSONSerializationJSONObjectWithData:data options:NSJSONReadingMutableContainerserror:&resultError];
NSLog(@"%@", result);
}];
}