NSMutableUrlRequest自定义封装网络请求

Posted aRenOuBa

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了NSMutableUrlRequest自定义封装网络请求相关的知识,希望对你有一定的参考价值。

1.首先封装一个自己的网络请求的类

**这里表视图引入了第三方类库:MJRefresh 上拉刷新下拉加载

这是.h文件

#import <Foundation/Foundation.h>

typedef void(^SuccessBlock)(NSData *data);
typedef void(^ErrorBlock)(NSError *error);

@interface RequestMethod : NSObject

@property (nonatomic, copy) SuccessBlock successBlock;
@property (nonatomic, copy) ErrorBlock errorBlock;



- (void)requestWithUrl:(NSString *)urlString rewuestType:(NSString *)type dictionary:(NSString *)dictionary successBlock:(SuccessBlock)successBlock errorBlock:(ErrorBlock)errorBlock;

+ (void)requestWithUrl:(NSString *)urlString rewuestType:(NSString *)type dictionary:(NSString *)dictionary successBlock:(SuccessBlock)successBlock errorBlock:(ErrorBlock)errorBlock;




@end

.m文件:

/参数字典转换成参数字符串的方法  转码之后就会得到body的NSData对象

- (NSData *)dataFromDictionary:(NSDictionary *)dictionary {
    
    NSMutableArray *mArray = [[NSMutableArray alloc] initWithCapacity:0];
    for (NSString *key in dictionary) {
        NSString *string = [NSString stringWithFormat:@"%@=%@",key,dictionary[key]];
        [mArray addObject:string];
    }

    NSString *newString = [mArray componentsJoinedByString:@"&"];
    return [newString dataUsingEncoding:NSUTF8StringEncoding];
    
}


+ (void)requestWithUrl:(NSString *)urlString requestType:(NSString *)type dictionary:(NSDictionary *)dictionary successBlock:(SuccessBlock)successBlock errorBlock:(ErrorBlock)errorBlock {
    
    NetHelper *helper = [[NetHelper alloc] init];
    [helper requestWithUrl:urlString requestType:type dictionary:dictionary successBlock:successBlock errorBlock:errorBlock];


}

//请求网络的方法

- (void)requestWithUrl:(NSString *)urlString requestType:(NSString *)type dictionary:(NSDictionary *)dictionary successBlock:(SuccessBlock)successBlock errorBlock:(ErrorBlock)errorBlock {

    //因为参数中的block执行的地方是异步请求 那么在Block执行之前 方法已经走完了 那么block就会被回收 所以需要声明属性来记录传入的block 就算是方法内部的block被回收了 也可以执行
    self.successBlock = successBlock;
    self.errorBlock = errorBlock;
    
    NSURLSession *session = [NSURLSession sharedSession];
    //创建对象 采用可变的网络请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    //如果请求方式是POST
    if ([type isEqualToString:@"POST"]) {
        [request setHTTPMethod:type];//设置请求方式
        if (dictionary.count != 0) {
            [request setHTTPBody:[self dataFromDictionary:dictionary]];
        }
        
    }
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error == nil) {
            self.successBlock(data);
        } else {
            self.errorBlock(error);
        }
        
    }];

    [task resume];

}

2.然后在表视图中使用

@interface ListTableViewController ()

@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic) NSUInteger count;

@end

@implementation ListTableViewController

- (NSMutableArray *)dataArray {
    if (_dataArray == nil) {
        _dataArray = [[NSMutableArray alloc] initWithCapacity:0];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadUpData)];
    //上拉加载
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadBottomData)];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"MyTableViewCell" bundle:nil] forCellReuseIdentifier:@"reuse"];
    
    
    
        // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)loadUpData {
    
    [NetRequestHelper requestWithUrl:@"http://api2.pianke.me/pub/shop" requestType:@"POST" dictionary:@{@"start":[NSString stringWithFormat:@"%ld",self.count += 10]} successBlock:^(NSData *data) {
        //解析
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *dataDic = dic[@"data"];
        //通过list这个key再取到数据保存的数组
        NSArray *array = dataDic[@"list"];
        for (NSDictionary *dic in array) {
            Model *model = [[Model alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.dataArray addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            //结束刷新
            [self.tableView.mj_header endRefreshing];
        });
        
    } errorBlock:^(NSError *error) {
        NSLog(@"刷新失败");
    }];


}

 

以上是关于NSMutableUrlRequest自定义封装网络请求的主要内容,如果未能解决你的问题,请参考以下文章

关于HTTP请求头

Nifi自定义processor

iOS广告轮播图

自定义View的封装

angular 自定义服务封装自定义http请求

封装 - 自定义控件