【发布时间】:2016-12-01 23:16:22
【问题描述】:
我正在尝试使用 AFNetowrking 发出 GET 请求。代码如下:
@property (nonatomic, readwrite) AFHTTPSessionManager *httpSessionManager;
...
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
_httpSessionManager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:self.baseURL]
sessionConfiguration:config];
_httpSessionManager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
_httpSessionManager.responseSerializer.acceptableContentTypes = [_httpSessionManager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
_httpSessionManager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
_httpSessionManager.securityPolicy.allowInvalidCertificates = YES;
...
NSMutableDictionary* parameters = [self defaultUserSessionParameters];
NSString *url = [self constructURLWithEndpointPath:@"lead_sources.json"];
RequestSuccessBlock winBlock = ^(NSURLSessionDataTask *task, id responseObject)
{
NSLog(@"GetLeadSources, response Object: %@", [responseObject description]);
NSArray* leadSources = responseObject[@"lead_sources"];
if (!leadSources)
{
NSString* errorString = @"Successfully retrieved lead sources but no values were returned!";
NSLog(@"%@",errorString);
NSError* error = [NSError bpdErrorWithDescription:errorString];
completion(nil, error);
}
else
{
completion(leadSources,nil);
}
};
RequestFailureBlock failureBlock = ^(NSURLSessionDataTask *task, NSError *error)
{
NSLog(@"FAILURE: get lead sources, Error: %@", error);
NSString* ErrorResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
NSLog(@"server error response: %@ /end", ErrorResponse);
};
[self.httpSessionManager GET:url
parameters:parameters
progress:nil
success:winBlock
failure:failureBlock];
但我每次都会收到此错误:
请求失败:不可接受的内容类型:text/html
我做了一些挖掘,发现这个错误是由于我的响应序列化程序而引发的,所以我添加了这一行来解决这个问题:
_httpSessionManager.responseSerializer.acceptableContentTypes = [_httpSessionManager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
但是当我添加这个时,我得到了以下错误:
JSON 文本未以数组或对象开头,并且允许未设置片段的选项。
为此,我发现我需要设置阅读选项以允许片段。我尝试将序列化程序设置为:
_httpSessionManager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
然后我得到另一个错误:
字符 0 周围的值无效
我想我必须将响应序列化程序设置为 AFHTTPResponseSerializer,但我似乎无法弄清楚如何使用该序列化程序允许片段。
无论如何,我认为这不是抛出 404 的原因。我相信我没有访问我尝试访问的域,并且 AFNetworking 在解析我正在访问的 url 引发的响应时遇到问题。
所以两个问题:
如何才能让序列化程序正确解析我的响应? (又名沉默这三个错误?)
为什么会抛出 404?我可以导航到它试图点击的网址,但它说页面不可用
提前致谢!
【问题讨论】:
标签: objective-c afnetworking afnetworking-3