iOS 网络请求 与 网络封装

<span style="font-family: Arial, Helvetica, sans-serif;">- (void)viewDidLoad {</span>
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    // Do any additional setup after loading the view.
    
    // 同步几乎不用 (POST 有密码等得页面)
    // 工作中一般用第三方 (这些都不用)
    
    NSArray * buttonArray = @[@"GET同步",@"POST同步",@"GET异步",@"POST异步"];
    
   // 创建Button按钮
    for (int i = 0; i < 4; i++) {
        UIButton * button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [button setFrame:CGRectMake(10 + i * 84, 100, 74, 44)];
        [button setTitle:buttonArray[i] forState:UIControlStateNormal];
        button.tag = 1000 + i;
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        button.backgroundColor = [UIColor greenColor];
        [self.view addSubview:button];
    }
}

- (void)buttonClick:(UIButton *)button
{
    switch (button.tag) {
        case 1000:
            NSLog(@"GET同步");
            [self GETsynchrnized];
            break;
        case 1001:
            NSLog(@"POST同步");
            [self POSTsynchrnized];
            break;
        case 1002:
            NSLog(@"GET异步");
            [self GETasynchrnized];
            break;
        case 1003:
            NSLog(@"POST异步");
            [self POSTasynchrnized];
            break;
            
        default:
            break;
    }
}

- (void)GETsynchrnized
{
    // 接受  网络地址
    NSString *UrlStr = @"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";
    // 转码
    NSString *strEncode = [UrlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    // 创建URL
    NSURL *url = [NSURL URLWithString:strEncode];
    // 网络请求
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
    // 服务器根据URL 返回数据
    NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil];
    // JSON 解析
    NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSLog(@"%@" , dic);
    
}

- (void)POSTsynchrnized
{
    NSString *urlString = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    // 设置请求类型,默认GET . POST 请求需要设置
    [urlRequest setHTTPMethod:@"POST"];
    NSString *bodyString = @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";
    NSData *bodyData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
    [urlRequest setHTTPBody:bodyData];
    
    NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil];
    NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSLog(@"%@" , dic);
    
}
- (void)GETasynchrnized{
    
    NSString *UrlStr = @"http://api.tudou.com/v3/gw?method=album.channel.get&appKey=myKey&format=json&channel=c&pageNo=1&pageSize=15";
    NSURL *url = [NSURL URLWithString:UrlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSLog(@"%@" , dic);
    }];
    
    
}
- (void)POSTasynchrnized
{
    NSString *str = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
    NSURL *url = [NSURL URLWithString:str];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    
    NSString *bodyStr = @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";
    NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    
}

新建立一个类,继承与NSObject, 我们在.h 文件中

// 声明协议
@protocol requestDelegate <NSObject>

- (void)requestdata:(id)data;

@end


@interface HttpRequest : NSObject

// 设置代理人属性
@property (nonatomic , assign)id<requestDelegate>delegate;

// 单例方法
+(HttpRequest *)httpRequestHandle;

// 
- (void)loadRequestWithUrl:(NSString *)urlString mothod:(NSString *)mothod pramar:(NSString *)pramar;

在.m 中 实现声明的这两个方法

+(HttpRequest *)httpRequestHandle
{
    static HttpRequest *http = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        http = [[HttpRequest alloc]init];
    });
    return http;
    
}
- (void)loadRequestWithUrl:(NSString *)urlString mothod:(NSString *)mothod pramar:(NSString *)pramar
{
    NSString *str = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:str];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    if ([mothod isEqualToString:@"POST"]) {
        [request setHTTPMethod:@"POST"];
        NSData *bodyData = [pramar dataUsingEncoding:NSUTF8StringEncoding];
        [request setHTTPBody:bodyData];
    }
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data) {
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            [self.delegate requestdata:result];
        }else{
            NSLog(@"请求数据失败");
        }
    }];

}

这样网络数据封装就完成了. 调用的时候用单例调用.  希望这篇能对大家有所帮助,Coco 在这里希望能够关注我~~谢谢





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值