//
// ViewController.m
// UI14_GET-POST
//
// Created by dllo on 15/8/17.
// Copyright (c) 2015年 zhozhicheng. All rights reserved.
//
#import ViewController.h
@interface ViewController ()
- (IBAction)synGET:(id)sender;
- (IBAction)synPOST:(id)sender;
- (IBAction)asynGET:(id)sender;
- (IBAction)asynPOST:(id)sender;
- (IBAction)block:(id)sender;
@property(nonatomic,retain)UIImageView *imageView;
@property(nonatomic,retain)NSMutableData *data;
@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(200, 100, 150, 150)];
self.imageView.backgroundColor =[UIColor cyanColor];
[self.view addSubview:self.imageView];
[_imageView release];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)synGET:(id)sender {
// NSLog(@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];
// NSLog(@%@,strEncode);
//接下來,URL符合要求之後,就開始進行網絡請求,網絡請求分為三步
//1.根據已經編碼好的URL,創建一個NSURL
NSURL *url = [NSURL URLWithString:strEncode];
//2.發送一個請求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//3.返回我們要的數據,一個NSData對象
//三個參數:第一個參數是剛剛創建的請求,第二個是返回的一個響應,第三個是錯誤信息
NSURLResponse *response = nil;
NSError *error =nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//對返回來的數據,data進行json解析
//把所有的銀行名都打印出來
NSMutableDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSMutableArray *arr = dic[@results];
for (NSDictionary *dic in arr) {
NSLog(@%@,dic[@name]);
}
}
- (IBAction)synPOST:(id)sender {
NSLog(@POST);
NSString *strURL =@http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx;
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解析
NSMutableDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@%@,dic);
}
- (IBAction)asynGET:(id)sender {
NSLog(@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];
//前兩步和之前還是一樣,第三步出現變化,通過代理的方式進行異步操作
[NSURLConnection connectionWithRequest:request delegate:self];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//只要接收到服務器返回的響應信息,就會走這個方法,我們在這個方法裡需要對接收數據的容器data進行初始化的設置
self.data = [NSMutableData data];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
//只要他返回數據,就會走這個方法
//append是累加的意思
[self.data appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//到這,整個請求已經結束,需要把返回的DATA對imageView的image進行賦值
self.imageView.image = [UIImage imageWithData:self.data];
}
#warning 同步和異步GET請求在步驟上完全相同,只是在第三步同步使用的是sendSyn方法,同步使用的是代理的方法,異步是基於同步進行操作
- (IBAction)asynPOST:(id)sender {
NSLog(@POST異步);
NSString *strURL =@http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx;
//1.創建NSUrl
NSURL *url = [NSURL URLWithString:strURL];
//2.請求
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url];
//3.request請求方式
[request setHTTPMethod:@POST];
NSString *bodyStr = @date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213;
NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
//添加到request
[request setHTTPBody:bodyData];
//
//網絡請求在子線程裡進行請求,請求下來的數據需要通過控件作為載體實現出來,需要把數據在主線程裡顯示,第二個參數就是指定把數據返回到那個線程
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//參數data就是我們請求下來的數據,接下來數據的解析就在block中進行操作
//json解析
NSMutableDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@%@,dic);
}];
}
- (IBAction)block:(id)sender {
NSLog(@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];
}];
}
@end
#warning 總結一下網絡請求的步驟:1.根據網址的字符串,創建一個NSURL對象,2.根據這個url對象,創建一個請求,3.發送請求,然後獲取請求對象,同步和異步的區別就是請求方法選用有差別,其他都一樣
#warning POST就是比GET多一個,需要request添加一個body