对NSURLSession进行网络请求方法封装
2016-05-26 17:01
513 查看
HJURLSession.h
HJURLSession.m
测试
// // HJURLSession.h // HJURLSession // // Created by 黄健 on 16/3/29. // Copyright © 2016年 黄健. All rights reserved. // #import <Foundation/Foundation.h> typedef enum { GET, POST } RequestMethod; typedef void(^ResponseBlock)(id responseObject); typedef void(^ErrorBlock)(id error); @interface HJURLSession : NSObject /** * @author 黄健, 2016-05-26 16:05:59 * * @brief 对NSURLSession进行封装的网络请求类 * * @param _string 请求接口 * @param _method 请求方式 * @param _params 请求参数 * @param _response 响应成功Block返回的数据 * @param _error 响应失败Block返回的数据 */ + (void)sessionWithString:(NSString *)_string method:(RequestMethod)_method params:(NSDictionary *)_params response:(ResponseBlock)_response error:(ErrorBlock)_error; @end
HJURLSession.m
// // HJURLSession.m // HJURLSession // // Created by 黄健 on 16/3/29. // Copyright © 2016年 黄健. All rights reserved. // #import "HJURLSession.h" @implementation HJURLSession + (void)sessionWithString:(NSString *)_string method:(RequestMethod)_method params:(NSDictionary *)_params response:(ResponseBlock)_response error:(ErrorBlock)_error { NSString *string; // 将字典类型的请求参数转化为字符串 NSString *params = [HJURLSession paramsToString:_params]; // 下面是根据接口文档的"实际情况"对接口进行拼接,请自行处理 if (_method == GET) { string = [NSString stringWithFormat:@"%@%@?%@", HOSTNAME, _string, params]; } else { string = [NSString stringWithFormat:@"%@%@", HOSTNAME, _string]; } // 对接口进行URL的编码 string = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]; NSURL *URL = [NSURL URLWithString:string]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL]; if (_method == GET) { [request setHTTPMethod:@"GET"]; } else { [request setHTTPMethod:@"POST"]; [request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]]; } [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { if (!error) { _response([NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]); } else { _error(error); } }] resume]; } + (NSString *)paramsToString:(NSDictionary *)dic { NSMutableArray *array = [NSMutableArray array]; for (NSString *key in dic) { NSString *value = [dic objectForKey:key]; [array addObject:[NSString stringWithFormat:@"%@=%@", key, value]]; } return [array componentsJoinedByString:@"&"]; } @end
测试
/** * @author 黄健, 2016-05-26 16:05:33 * * @brief 对首页接口进行GET请求,并要求显示第一页的5条数据 */ NSDictionary *params = @{@"page":@"1", @"page_size":@"5"}; [HJURLSession sessionWithString:@"index" method:GET params:params response:^(id responseObject) { NSLog(@"%@", responseObject); } error:^(id error) { NSLog(@"%@", error); }];