基于AFNetworking3.0的网络封装

时间:2022-03-12 14:28:45

1.创建名为HTTPMethod(自己随便起名字)的头文件

2.导入AFNetworking头文件(在github上下载最新版):

    #import "AFNetworking.h"

3.在.h文件里声明类方法:

    //参数解释:(1)urlString是你想请求的网址   (2)bodyDic是POST请求时的参数   (3)dataBlock是数据请求成功后用来回调数据的block

    + (void)getDataByString:(NSString *)urlString BodyDic:(NSDictionary *)bodyDic WithDataBlock:(void(^)(id data))dataBlock;

4.方法的实现:

+(void)getDataByString:(NSString *)urlString BodyDic:(NSDictionary *)bodyDic WithDataBlock:(void (^)(id))dataBlock

{

//(1).字符串的转码

urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:urlString]];

//(2).创建管理者对象(session)

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

//(3).设置允许请求的类别

manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html", @"application/javascript", @"text/js", nil];

//(4).开始请求

if (!bodyDic) {

//如果bodyDic为空就执行get请求

[manager GET:urlString parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {

dataBlock(responseObject);

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

NSLog(@"请求失败");

}];

}

else

{

[manager POST:urlString parameters:bodyDic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {

dataBlock(responseObject);

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

NSLog(@"请求失败");

}];

}

}