iOS 数据请求 同步get 同步post 异步get 异步post

1  同步get请求。《get的请求不需要httpbody, 而post请求需要指定 httpbody》


- (IBAction)syncGETAction:(id)sender {

    //  同步GET请求

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

    //  1产生一个请求

    

    //  请求地址

   NSURL *url = [NSURLURLWithString:path];

    //  参数1:请求地址

    //  参数2:缓存celue  缓存策略 服务器NSURLRequestUseProtocolCachePolicy

    //  参数3:超时时间

    NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:urlcachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:60];

    //  2对请求进行设置

    

    //  请求方式:get / post

    request.HTTPMethod =@"GET";

    

    //  3进行网络连接

    

    // 连接服务器的两种方式:同步/异步

    

    //  同步连接

    

   NSURLResponse *response =nil;

   NSError *error =nil;

    NSData *data = [NSURLConnectionsendSynchronousRequest:requestreturningResponse:&responseerror:&error];/* 如果是图片 

    imageWithData, 如果是 txt  就用解析*/

    // 链接服务器的相关信息

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

   if (error !=nil) {

       NSLog(@"错误信息:%@", error);

    }

    //  通过data产生一个图片

   UIImage *image = [UIImageimageWithData:data];

   self.imageView.image = image;

    // status code: 状态码200 请求成功

}


2  同步post 请求 《需要指定 httpbody


- (IBAction)syncPOSTAction:(id)sender {

    //  post请求,同步链接服务器

    //  1创建请求

    

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

    //  将字符串转为url

    

   NSURL *url = [NSURLURLWithString:str];

    

    //  建立请求对象

    

    NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:urlcachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:60];

    

    //  设定请求方式

    request.HTTPMethod =@"POST";

    //  设定请求body

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

    //  bodyStr转换为NSData类型

    NSData *bodyData = [bodyStrdataUsingEncoding:NSUTF8StringEncoding];

    //  设置请求的bodynsdata

    request.HTTPBody = bodyData;

    

    //  2连接服务器

    

   NSURLResponse *response =nil;

   NSError *error =nil;

   NSData *data = [NSURLConnectionsendSynchronousRequest:requestreturningResponse:&responseerror:&error];

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

   if (error !=nil) {

       NSLog(@"错误信息%@", error);

    }

    //  3将结果转换为字符串

    NSString *resultStr = [[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding];

   NSLog(@"post请求的结果:%@", resultStr);

    

    NSMutableDictionary *dic = [NSJSONSerializationJSONObjectWithData:dataoptions:NSJSONReadingMutableContainerserror:nil];

    

}


3 异步get请求 《NSURLConnectionDataDelegate》


- (IBAction)asyncGETAction:(id)sender {

    

    //  get请求方式:异步连接服务器

    // 异步:不会卡死界面

    //  1生成一个请求

    

    NSURL *url = [NSURLURLWithString:@"http://pic13.nipic.com/20110313/2686941_211532129160_2.jpg"];

    //  建立请求对象

    NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:urlcachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:60];

    request.HTTPMethod =@"GET";

    //  2链接服务器

    // 异步链接的方式 协议回调实现异步链接

    //  参数1:请求对象

    // 参数2:指定一个代理人

    [NSURLConnectionconnectionWithRequest:requestdelegate:self];

}

#pragma mark - 异步连接服务器的协议方法


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

{

    NSLog(@"%s",__FUNCTION__);

    // 收到服务器的响应信息

    NSLog(@"收到服务器响应");

    

    //  data数据进行初始化

    self.data = [NSMutableDatadata];

}


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

{

    NSLog(@"%s",__FUNCTION__);

    //  收到数据

   NSLog(@"接收数据");

    [self.dataappendData:data];

    

}



- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    NSLog(@"%s",__FUNCTION__);

    //  接收数据完毕

   NSLog(@"完毕");

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

   self.imageView.image = image;

}



4 异步post方法



- (IBAction)asyncPOSTAction:(id)sender {

    

    

    

    //  post请求方式 :异步连接服务器

    //  post请求,同步链接服务器

    //  1创建请求

    

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

    

    //  将字符串转为url

    

   NSURL *url = [NSURLURLWithString:str];

    

    //  建立请求对象

    NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:urlcachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:60];

    

    //  设定请求方式

    request.HTTPMethod =@"POST";

    

    //  设定请求body

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

    

    //  bodyStr转换为NSData类型

    NSData *bodyData = [bodyStrdataUsingEncoding:NSUTF8StringEncoding];

    

    //  设置请求的bodynsdata

    request.HTTPBody = bodyData;

    

    //  2异步连接服务器 block回调

    

    //  参数1:请求

    //  参数2:操作队列

    //  参数3:block回调

    [NSURLConnectionsendAsynchronousRequest:requestqueue:[NSOperationQueuemainQueue]completionHandler:^(NSURLResponse *response,NSData *data,NSError *connectionError) {

        NSMutableDictionary *dic = [NSJSONSerializationJSONObjectWithData:dataoptions:NSJSONReadingMutableContainerserror:nil];

       NSLog(@"请求结果:%@", dic);

    }];


    

}









//////////////////////////////////////////////////


//    封装请求(方便调用)


//

//  NetWorkingHandle.m

//  数据持久化作业

//

//  Created by yangtingting on 14-7-28.

//  Copyright (c) 2014 灭神科技. All rights reserved.

//


#import "NetWorkingHandle.h"



@implementation NetWorkingHandle



- (instancetype)init

{

    self = [super init];

    if (self) {

        

    }

    return self;

}

- (void)getDataWithURLString:(NSString *)str  completion: (Block)netBlock

{

    

    self.netBlock = netBlock;

    

    //  通过外部传入的参数 创建请求

    NSURL *url = [NSURL URLWithString:str];

    

    //  建立请求对象

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

    

    //  设定请求方式

    request.HTTPMethod = @"GET";

    

    //  建立网络连接 (异步)

    

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

        

        NSError *error = nil;

        

        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];

        

        self.netBlock (result);

        

    }];

}


- (void)getdatawithIDS:(NSString *)ids  completion: (Block)netBlock

{

    self.netBlock = netBlock;

    NSMutableString *string = [NSMutableString  stringWithString:@"http://api.douban.com/v2/movie/subject/24879858?apikey=0df993c66c0c636e29ecbb5344252a4a&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&app_name=doubanmovie"];

    

    //  拼接string 网址

    [string replaceOccurrencesOfString:@"24879858" withString:ids options:NSCaseInsensitiveSearch range:NSMakeRange(0, [string length])];

    

    //  转码之后的pathstring

    [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    


}

- (void)dealloc

{

    

    Block_release(_netBlock);

    [super dealloc];

}



@end



在主界面的调用这个类的方法


[net getDataWithURLString:self.stringpic completion:^(id result) {

        

        self.dic = result;

        

        NSLog(@"%@", self.dic);

        

        self.numOf =  [[result objectForKey:@"products"] count];

        

        //        NSLog(@"%d", self.numOf);

        

        self.arr = [result objectForKey:@"products"];

        

        

        self.collectionview = [[UICollectionView alloc]                           initWithFrame:CGRectMake(0, 90, 320, 390) collectionViewLayout:layout];

        

        

        self.collectionview.delegate = self;

        

        self.collectionview.dataSource = self;

        

        [self.view addSubview:self.collectionview];

        

        [self.collectionview release];

        

        

        [self.collectionview registerClass:[MyCell class] forCellWithReuseIdentifier:@"reuse"];

        

        

    }];

    








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值