对NSURLSession进行网络请求方法封装

  • HJURLSession.h

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


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值