为什么AFNetworking总是进入Failure块?

时间:2016-04-19 23:58:53

标签: ios objective-c afnetworking-3

我在我的项目中集成了here的AFNetworking。但是当我使用AFNetworking获得请求时,它总是会进入Failure块。以下是我的代码。请让我知道,我在这里做错了什么?

NSString *baseUrl = @"http://www.nactem.ac.uk/software/acromine/dictionary.py?sf=ETA";
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:baseUrl parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);

   //Always it invoke the Failure block
    }failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSHTTPURLResponse *response = error.userInfo[AFNetworkingOperationFailingURLResponseErrorKey];
        NSInteger statusCode = response.statusCode;
        NSLog(@"Error Code=%ld",statusCode);
        NSLog(@"Desc=%@",response.description);
    }];

注意: - 这是有效的网址。 http://www.nactem.ac.uk/software/acromine/dictionary.py?sf=ETA

以下是错误代码和说明: -

Error Code 200
Error Description <NSHTTPURLResponse: 0x7fbab8509860> { URL: http://www.nactem.ac.uk/software/acromine/dictionary.py?sb=hmm } { status code: 200, headers {
    Connection = close;
    "Content-Type" = "text/plain; charset=UTF-8";
    Date = "Wed, 20 Apr 2016 00:17:27 GMT";
    Server = "Apache/2.2.15 (Scientific Linux)";
    "Transfer-Encoding" = Identity;
} }

3 个答案:

答案 0 :(得分:1)

我找到了答案: -

NSString *url = @"http://www.nactem.ac.uk/software/acromine/dictionary.py?sf=hmm";
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

//Missing this line (Any request or response serializer dealing with HTTP is encouraged to subclass)
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseObject
                                                             options:kNilOptions
                                                               error:&error];
        NSLog(@"Success= %@",json);

    }failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSHTTPURLResponse *response = error.userInfo[AFNetworkingOperationFailingURLResponseErrorKey];
        NSInteger statusCode = response.statusCode;
        NSLog(@"Fail=%ld",statusCode);
    }];

答案 1 :(得分:0)

查看错误说明,您将看到有用的解释

  

Domain = com.alamofire.error.serialization.response Code = -1016&#34;请求失败:不可接受的内容类型:text / plain&#34;

正确的解决方法是制作内容类型application/json,因为它看起来似乎是JSON。

答案 2 :(得分:0)

问题在于AFNetworking正在寻找的响应类型。如果您明确告诉它期望文本/普通响应,那么您应该执行成功回调。您在 经理 对象的初始位置后面的以下代码行应该执行以下操作:

manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];