AFNetworking获取完整的error body

2018-09-25  本文已影响0人  YANGXIXIYear

最近在做项目的版本迭代,有些接口的数据请求前一秒都是对的,后一面就报返回的数据不是json类型,后台服务器说没修改,这就让我很懵了,服务端自测和安卓端测试都没毛病,难道真的是我的网络请求有问题?很疑惑!!!打印error的信息,只有status code和简短的说明,根本不知道具体的原因,服务端说能不能给他们看请求返回的body,我赶紧去查看AFNetworking中error的相关属性,发现并没有body相关的内容,后来在网上搜到了一篇文章AFNetworking如何获取完整的error body(感谢这位朋友☺️),我立马测试了一下,真的可以!!!下面是我的测试代码:

继承AFJSONResponseSerializer新建一个类JsonResponseSerializer

1、JsonResponseSerializer.h

#import "AFURLResponseSerialization.h"

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

static NSString * const JSONResponseSerializerWithBodyKey = @"statusCode";

@interface JsonResponseSerializer : AFJSONResponseSerializer

@end

2、JsonResponseSerializer.m添加方法

- (id)responseObjectForResponse:(NSURLResponse *)response
                           data:(NSData *)data
                          error:(NSError *__autoreleasing *)error
{
    
    id JSONObject = [super responseObjectForResponse:response data:data error:error]; // may mutate `error`
    
    if (*error != nil) {
        
        NSMutableDictionary *userInfo = [(*error).userInfo mutableCopy];
        
        [userInfo setValue:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] forKey:JSONResponseSerializerWithDataKey];
        
        [userInfo setValue:[response valueForKey:JSONResponseSerializerWithBodyKey] forKey:JSONResponseSerializerWithBodyKey];
        
        NSError *newError = [NSError errorWithDomain:(*error).domain code:(*error).code userInfo:userInfo];
        (*error) = newError;
    }
    
    return JSONObject;
}

3、用法,在请求之前为manager添加代码:

manager.responseSerializer = [JsonResponseSerializer serializer];
上一篇下一篇

猜你喜欢

热点阅读