-1

我已经在我的项目中集成了 AFNetworking 。但是当我使用 AFNetworking 收到请求时,它总是会进入失败块。下面是我的代码。请让我知道,我在这里做错了什么?

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);
    }];

注意:- 这是有效的 URL。 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;
} }
4

3 回答 3

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);
    }];
于 2016-04-20T01:29:29.180 回答
0

查看错误描述,您会看到有用的解释

Domain=com.alamofire.error.serialization.response Code=-1016 “请求失败:不可接受的内容类型:文本/纯文本”

正确的解决方法是制作 content-type application/json,因为它确实看起来是 JSON。

于 2016-04-20T00:58:56.227 回答
0

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

manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
于 2016-04-20T01:37:28.207 回答