基于AFNetWorking封装一个网络请求数据的类

1.新建一个继承于NSObject类的类,在.h文件中

#import "AFHTTPRequestOperationManager.h"

//定义两个block来接收请求成功和失败

typedef  void(^DownLoadFinishedBlock)(id responseObj);

typedef void (^DownLoadFialedBlock)(NSError*error);

 

@interface NetManager : NSObject

 

//Get请求的方法封装

+(void)doGetWithUrlStr:(NSString*)urlString contentType:(NSString*)type finished:(DownLoadFinishedBlock)finished failure:(DownLoadFialedBlock)fialed;

//Post请求的方法封装

+(void)doPostWithUrlStr:(NSString*)urlString parameters:(NSDictionary*)dic contentType:(NSString*)type finished:(DownLoadFinishedBlock)finished failure:(DownLoadFialedBlock)fialed;

 

 

2.下面是封装方法的实现:

#import "NetManager.h"

 

@implementation NetManager

 

//Get请求的方法

+(void)doGetWithUrlStr:(NSString*)urlString contentType:(NSString*)type finished:(DownLoadFinishedBlock)finished failure:(DownLoadFialedBlock)fialed{

 

  //创建manager对象

    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];

  //设置请求的数据类型

    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:type, nil];

    [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

  //请求成功

        finished(responseObject);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

  //请求失败

        fialed(error);

    }];

}

 

//Post请求的方法

//说明:parameters:参数,即使用post请求时需要传给后台服务器的参数,在这里我们应封装成一个字典类型的数据,然后把这个字典当做参数传过去。

 

+(void)doPostWithUrlStr:(NSString*)urlString parameters:(NSDictionary*)dic contentType:(NSString*)type finished:(DownLoadFinishedBlock)finished failure:(DownLoadFialedBlock)fialed

{

  //创建manager对象  

    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];

  //设置请求的数据类型  

    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:type, nil];

    [manager POST:urlString parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {

         finished(responseObject);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        fialed(error);

    }];

}

 

 

 

 

 

@end

posted @ 2016-03-18 15:50  Mr.pengge  阅读(484)  评论(3编辑  收藏  举报