#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
#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];
}
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);
}];