AFNetworking设置请求头 处理数据乱码

直接上代码了:

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    //设置请求头

    AFHTTPRequestSerializer*requestSerializer =  [AFJSONRequestSerializer serializer];

    NSDictionary *headerFieldValueDictionary2 = @{@"COOKIE":@"PHPSESSID=1523241822154"};

    if (headerFieldValueDictionary2 != nil) {

        for (NSString *httpHeaderField in headerFieldValueDictionary2.allKeys) {

            NSString *value = headerFieldValueDictionary2[httpHeaderField];

            [requestSerializersetValue:value forHTTPHeaderField:httpHeaderField];

        }

    }

    manager.requestSerializer = requestSerializer;

请求体:

 [managerPOST:[MainURL stringByAppendingString:url] parameters:dict constructingBodyWithBlock:^(id  _Nonnull formData) {

                }progress:^(NSProgress * _Nonnull uploadProgress) {

  }success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {      

              NSLog(@"responseObject===%@",responseObject);       

//如果返回的    responseObject为乱码 处理如下:

/*NSError *errorData;

 NSString* strdata = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];//在将NSString类型转为NSData

 NSData * data =[strdata dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

 NSDictionary *dict22 = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorData];

 NSLog(@"dict22==%@",dict22);

*/

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

               }];

如果想子类话AFN 可以这样写

#import

#import "AFNetworking.h"

@interface XHWHTTPManager : AFHTTPSessionManager

@end

#import "XHWHTTPManager.h"

@implementation XHWHTTPManager

- (instancetype)initWithBaseURL:(NSURL*)url sessionConfiguration:(NSURLSessionConfiguration*)configuration{

    if (self = [super initWithBaseURL:url sessionConfiguration:configuration]) {

        //设置想要的请求头信息

        //什么设备

        [self.requestSerializer setValue:[UIDevice currentDevice].model forHTTPHeaderField:@"Phone"];

        //什么系统

        [self.requestSerializer setValue:[UIDevice currentDevice].systemName forHTTPHeaderField:@"OS"];

    }

    return self;

}

@end

个人强烈建议使用时 类加载 AFN

@property (nonatomic,strong) AFHTTPSessionManager *manager;

- (AFHTTPSessionManager *)manager{

    if(!_manager) {

        _manager = [AFHTTPSessionManager manager];

    }

    return _manager;

}

你可能感兴趣的:(AFNetworking设置请求头 处理数据乱码)