封装Ger网络请求

//

//  Connection.h


//

//  Created by 毛连帅 on 14-6-24.

//  Copyright (c) 2014年 毛帅. All rights reserved.

//


#import <Foundation/Foundation.h>


typedef void(^FinishedBlock) (NSData *data);


@interface Connection : NSObject<NSURLConnectionDataDelegate,NSURLConnectionDelegate>


@property (nonatomic,retain) NSMutableData * dataArray;


@property (nonatomic,copy) FinishedBlock finished;

// 直接调用这个类方法即可实现网络请求(注:URLStr表示需要传过来的网址)

+ (void)connectionGetWithURL:(NSString *)URLStr block:(FinishedBlock)block;


@end



//

//  Connection.m


//

//  Created by 毛连帅 on 14-6-24.

//  Copyright (c) 2014 毛帅. All rights reserved.

//


#import "Connection.h"


@implementation Connection


- (void)dealloc

{

    [_dataArray release];

    _dataArray = nil;

    [super dealloc];

}

// 初始化网络对象

- (instancetype)init

{

    self = [super init];

    if (self) {

        _dataArray = [[NSMutableData alloc] init];

    }

    return self;

}


// 获得网址并进行网络请求

+ (void)connectionGetWithURL:(NSString *)URLStr block:(FinishedBlock)block {

    Connection * conn = [[Connection alloc] init];

    conn.finished = block;

    // 网络请求

    [conn startGetWithUrl:URLStr];

    [conn release];

}

// 开始网络请求

- (void)startGetWithUrl:(NSString *)url {

    NSURL * currentUrl = [NSURL URLWithString:url];

    

    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:currentUrl];

    // 设置网络请求方式

    [request setHTTPMethod:@"GET"];

    // 开始网络请求

    [NSURLConnection connectionWithRequest:request delegate:self];

}

// 开始响应

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

    

}

// 接受二进制数据

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

    [_dataArray appendData:data];

}

// 接受完成时运行

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

    // 返回数据

    self.finished(_dataArray);

}

// 异常时运行

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {

    NSLog(@"网络连接异常");

}




@end


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值