网络请求

#import <UIKit/UIKit.h>


@interface MainViewController : UIViewController<NSURLConnectionDataDelegate>


@property (nonatomic ,retain)UIImageView *imageView;

@property (nonatomic ,retain)NSMutableData *data;


@end



#import "MainViewController.h"


@interface MainViewController ()


@end


@implementation MainViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {

        // Custom initialization

        

        self.imageView = [[UIImageView alloc] initWithFrame:(CGRectMake(20, 20, 280, 300))];

        self.imageView.backgroundColor = [UIColor cyanColor];

        [self.view addSubview:self.imageView];

        [_imageView release];

        

       

    }

    return self;

}


- (void)viewDidLoad

{

    [super viewDidLoad];

    // Do any additional setup after loading the view.

    UIButton *button = [UIButton buttonWithType:(UIButtonTypeSystem)];

    [button setFrame:(CGRectMake(20, 330, 100, 60))];


    [button setTitle:@"同步GET" forState:(UIControlStateNormal)];

    [button addTarget:self action:@selector(syncGETAction:) forControlEvents:(UIControlEventTouchUpInside)];

    [self.view addSubview:button];

    

    UIButton *button1 = [UIButton buttonWithType:(UIButtonTypeSystem)];

    [button1 setFrame:(CGRectMake(200, 330, 100, 60))];


    [button1 setTitle:@"同步PSOT" forState:(UIControlStateNormal)];

    [button1 addTarget:self action:@selector(syncPOSTAction:) forControlEvents:(UIControlEventTouchUpInside)];

    [self.view addSubview:button1];

    

    UIButton *button2 = [UIButton buttonWithType:(UIButtonTypeSystem)];

    [button2 setFrame:(CGRectMake(20, 400, 100, 60))];


    [button2 setTitle:@"异步GET" forState:(UIControlStateNormal)];

     [button2 addTarget:self action:@selector(asyncGETAction:) forControlEvents:(UIControlEventTouchUpInside)];

    [self.view addSubview:button2];

    

    UIButton *button3 = [UIButton buttonWithType:(UIButtonTypeSystem)];

    [button3 setFrame:(CGRectMake(200, 400, 100, 60))];


    [button3 setTitle:@"异步POST" forState:(UIControlStateNormal)];

    [button3 addTarget:self action:@selector(asyncPOSTAction:) forControlEvents:(UIControlEventTouchUpInside)];

    [self.view addSubview:button3];

    

    

}


- (void)dealloc

{


    [_imageView release];

    [_data release];

    [super dealloc];


    

}


- (void)syncGETAction:(UIButton *)sender

{

    // 同步GET

    // 1.拼接网络地址

    NSString *str = @"http://cdn.gq.com.tw.s3-ap-northeast-1.amazonaws.com/userfiles/images_A1/6954/2011100658141857.jpg";

    

    // 2.将地址转为URL对象

    NSURL *url = [NSURL URLWithString:str];

    

    // 3.创建一个请求(request)

    // 参数1: 请求地址(NSRUL)

    // 参数2: 给请求选择一个缓存策略

    // 参数3: 请求超时的时间

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:30.0];

    // 4.给请求 设置 请求方式

    [request setHTTPMethod:@"GET"];

    // 5.将请求发送给服务器

    // 同步连接

    // 参数1: 请求(request)

    // 参数2: 响应信息

    // 参数3: 错误信息

    // 同步连接的方法 会一直等待 数据完整之后才继续执行

    NSError *error = nil;

    NSURLResponse *response = nil;

    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

    

    // 在这里获得的是完整的 data数据

    

    NSLog(@"服务器响应信息: %@", response);

    

    // 使用NSData数据

    UIImage *imamge = [UIImage imageWithData: data];

    self.imageView.image = imamge;

}



- (void)syncPOSTAction:(UIButton *)sender

{

    

    

    // 同步POST

    NSString *str = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";

    

    NSURL *url = [NSURL URLWithString:str];

    

    // 创建请求

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.f];

    

    // 设置请求方式

    [request setHTTPMethod:@"POST"];

    //产生一个body

    NSString *bodyStr = @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";

    

    NSData *data = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];

    // 设置post请求 附带的数据

    [request setHTTPBody:data];

    

    //发送请求

    NSURLResponse *response = nil;

    NSData *dataBack = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];

//    NSLog(@"%@", response);

    // 测试返回数据内容

    NSString *result = [[NSString alloc] initWithData:dataBack encoding:NSUTF8StringEncoding];

    NSLog(@"%@", result);

    

//   NSDictionary *dic =  [NSJSONSerialization JSONObjectWithData:dataBack options:NSJSONReadingMutableContainers error:nil];

//    NSLog(@"%@",dic);

}


- (void)asyncGETAction:(UIButton *)sender

{

    // 异步GET

    // 1.产生请求

    NSString *str = @"http://pic13.nipic.com/20110313/2686941_211532129160_2.jpg";

    NSURL *url = [NSURL URLWithString:str];

    

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.f];

    

    [request setHTTPMethod:@"GET"];

    

    // 2.建立连接

    // 异步连接 不会卡死界面

    // 参数1: 设定好的请求

    // 参数2: 设定网络代理人

    [NSURLConnection connectionWithRequest:request delegate:self];

    

}


// 当收到服务器的响应信息的时候 调用

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

    NSLog(@"%s",__FUNCTION__);

    // 当每次需要接收新的数据的时候 初始化data属性

     self.data = [NSMutableData data];

    

}

// 当接收服务器发送来的 data数据块 的时候 调用

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

      NSLog(@"%s",__FUNCTION__);

    [self.data appendData:data];

    

}

// 当数据接收完毕的时候调用

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{


      NSLog(@"%s",__FUNCTION__);

    // 调用这个方法说明 self.data属性已经是一个完整的数据

    UIImage *image = [UIImage imageWithData:self.data];

    self.imageView.image = image;

    

    

}




- (void)asyncPOSTAction:(UIButton *)sender

{

   // 异步POST

    

    NSString *str = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";

    NSURL *url = [NSURL URLWithString:str];

    

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];

   // 设置请求方式: POST

    [request setHTTPMethod:@"POST"];

    // 设置body

    NSString *bodayStr = @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";

    

    

    NSData *bodyData = [bodayStr dataUsingEncoding:NSUTF8StringEncoding];

    [request setHTTPBody:bodyData];

  

    

    // 2.连接

    // block基础上的异步连接

    

    // 参数1: 请求

    // 参数2: 返回主线程

    // 参数3:

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

       // 当异步连接完毕 而且 请求道完整的数据(参数data)之后 才执行这个块的内容

        

       // 在这个块中 写处理数据的代码 (解析/转为image/音频/视频)

        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];

//        NSLog(@"%@",dic);

//        NSLog(@"%@",NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES));

    }];

    

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值