AFNetworking 3.0 Code=-1016 错误解决方案

  • OC-GET请求方式代码
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:@"https://www.baidu.com/" parameters:nil headers:@{} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"成功----%@",[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"失败----%@",error);
    }];

会妥妥的报错

Domain=com.alamofire.error.serialization.response 
Code=-1016 "Request failed: unacceptable content-type: text/html" 
UserInfo={NSLocalizedDescription=Request failed: unacceptable content-type: text/html, NSErrorFailingURLKey=https://www.baidu.com/, com.alamofire.serialization.response.error.data

百度错误会让你添加一句这个代码

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

但是还会报其他错误

Domain=NSCocoaErrorDomain Code=3840 
"JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

为了从根本上解决Code=-1016错误,并避免Code=3840 错误,其实只需要一行代码:

// 添加这句代码
manager.responseSerializer = [AFHTTPResponseSerializer serializer];

GET实例代码(POST请求方式同理):

- (void)get {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 添加这句代码
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:@"https://www.baidu.com/" parameters:nil headers:@{} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"成功----%@",[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"失败----%@",error);
    }];
}

你可能感兴趣的:(AFNetworking 3.0 Code=-1016 错误解决方案)