AFNetworking 500响应机构 [英] AFNetworking 500 response body

查看:112
本文介绍了AFNetworking 500响应机构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在我的应用中使用AFNetworking 2.0。
我注意到如果我的网络服务返回500状态代码,我就不会得到响应的正文。

I've been using AFNetworking 2.0 in my app. I've noticed that if my web-service returns a 500 status code I do not get the body of the response.

这是我的一个例子php代码

Here is an example of my php code

try
{
    $conn = new PDO( "sqlsrv:server=$serverName;Database = $database", $uid, $pwd);
    $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    return $conn;
}

catch( PDOException $e )
{
    $response->status(500);
    echo( "Connection Error: " . $e->getMessage() );
}

如果我使用简单的休息客户端,这是一个响应体的示例。

If I use a simple rest client this is an example of a response body.

Connection Error: SQLSTATE[08001]: [Microsoft][SQL Server Native Client 11.0]SQL Server Network Interfaces: Error Locating Server/Instance Specified [xFFFFFFFF]. 

然而,这似乎是我从AFNetworking获得的唯一回复

However this seems to be the only response I can get from AFNetworking

Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x15e58fa0 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

这是我的Objective-c代码的一部分。

This is the part of my objective-c code that does this.

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

        NSLog(@"%@",error.description);

    }];

有没有办法可以获得回复正文?

Is there a way I can get the response body?

编辑:更多代码澄清

以下是我的AFHTTPSessionManager子类的一部分

Below is part of my subclass of AFHTTPSessionManager

@implementation MSMAMobileAPIClient

    + (MSMAMobileAPIClient *)sharedClient {
        static MSMAMobileAPIClient *_sharedClient = nil;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _sharedClient = [[MSMAMobileAPIClient alloc] initWithDefaultURL];
        });

        return _sharedClient;
    }

    - (id)initWithDefaultURL {
        return [self initWithBaseURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://%@/mamobile/index.php/" ,[[NSUserDefaults standardUserDefaults] stringForKey:@"serviceIPAddress"]]]];
    }

    - (id)initWithBaseURL:(NSURL *)url {

        self = [super initWithBaseURL:url];
        if (!self) {
            return nil;
        }
        self.responseSerializer = [AFCompoundResponseSerializer compoundSerializerWithResponseSerializers:@[[AFJSONResponseSerializer serializer], [AFHTTPResponseSerializer serializer]]];

        return self;
    }

我尝试将响应序列化器设置为AFCompoundResponseSerializer但它似乎没有有所作为

I tried setting the response serializer to a AFCompoundResponseSerializer but it didn't seem to make a difference

以下是我称之为图书馆员的子类示例。

Below is an example of a subclass that I call the Librarian.

-(void)searchForItemWithString:(NSString *)searchString withCompletionBlock:(arrayBlock)block {

    self.inventorySearchBlock = block;

    NSDictionary *parameters = @{@"query": searchString};

    [[MSMAMobileAPIClient sharedClient] GET:@"inventory/search" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {

        if (!responseObject) {
            NSLog(@"Error parsing JSON");
        } else {
            //do stuff with the json dictionary that's returned..
        }

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

        NSLog(@"Error: %@",error.description);

    }];

}


推荐答案

更新:我创建了一个github存储库来包含我正在使用的最新代码。所有更改都将在那里发布。 https://github.com/Hackmodford/HMFJSONResponseSerializerWithData

UPDATE: I have created a github repository to contain the latest code I am using. All changes will be posted there. https://github.com/Hackmodford/HMFJSONResponseSerializerWithData

答案来自github上的这个问题。
https://github.com/AFNetworking/AFNetworking/issues/1397

The answer comes from this issue on github. https://github.com/AFNetworking/AFNetworking/issues/1397

gfiumara是想出这个的开发者。我只是稍微修改了他的AFJSONResponseSerializer的子类来包含一个实际的字符串而不是NSData

gfiumara is the dev who came up with this. I have only slightly modified his subclass of AFJSONResponseSerializer to include an actual string instead of the NSData

//MSJSONResponseSerializerWithData.h

#import "AFURLResponseSerialization.h"

/// NSError userInfo key that will contain response data
static NSString * const JSONResponseSerializerWithDataKey = @"JSONResponseSerializerWithDataKey";

@interface MSJSONResponseSerializerWithData : AFJSONResponseSerializer

@end



< hr>


//  MSJSONResponseSerializerWithData.m

#import "MSJSONResponseSerializerWithData.h"

@implementation MSJSONResponseSerializerWithData

- (id)responseObjectForResponse:(NSURLResponse *)response
                           data:(NSData *)data
                          error:(NSError *__autoreleasing *)error
{
    if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
        if (*error != nil) {
            NSMutableDictionary *userInfo = [(*error).userInfo mutableCopy];
            userInfo[JSONResponseSerializerWithDataKey] = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSError *newError = [NSError errorWithDomain:(*error).domain code:(*error).code userInfo:userInfo];
            (*error) = newError;
        }

        return (nil);
    }

    return ([super responseObjectForResponse:response data:data error:error]);
}

@end

以下是一个示例我在故障块中使用它。

Here is an example of how I use it in the failure block.

} failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@",[error.userInfo objectForKey:@"JSONResponseSerializerWithDataKey"]); 
    }];

这篇关于AFNetworking 500响应机构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆