AFN如何添加请求头header和body

今天更新一下博客,之前有很多朋友问我AFNetworking 3.0舍弃了旧的方法,3.0是怎么添加“header” 和 请求体“body”的,很抱歉前段时间一直处于非常忙碌的状态,今天好不容易抽空更新下博客,希望对大家有所帮助。

一、3.0之前版本

1、首先,AFN是要在arc下使用的,所以非arc需添加 -objc-arc
2、其次,导入相应的库:
CoreLocation.framework
SystemConfiguration.framework
MobileCoreServices.framework
Security.framework
3、其实AFN请求也是继承NSURLRequest的,所以请求代码如下,不做详细解释了,直接贴代码。

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:XXX];
[request setValue:@"XXX" forHTTPHeaderField:@"nop"];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {

    NSLog(@"%@", responseObject);
} failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
    NSLog(@"%@",error);
}];
[op start];

二、3.0版本(更新)

AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
AFHTTPRequestSerializer *requestSerializer =  [AFJSONRequestSerializer serializer];

NSDictionary *headerFieldValueDictionary = @{@"version":@"1.0"};
if (headerFieldValueDictionary != nil) {
    for (NSString *httpHeaderField in headerFieldValueDictionary.allKeys) {
        NSString *value = headerFieldValueDictionary[httpHeaderField];
        [requestSerializer setValue:value forHTTPHeaderField:httpHeaderField];
    }
}
manger.requestSerializer = requestSerializer;
[manger GET:@"url" parameters:nil  progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
       
   } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       
}];

你可能感兴趣的:(AFN如何添加请求头header和body)