我在我的 iOS 应用程序中使用 AFNetworking 处理 HTTP 请求。我遇到了绊脚石。我无法确定响应内容类型是什么,但您必须在处理请求之前设置响应序列化程序。这意味着我可以执行 API 请求,期望返回图像,但实际上存在一些身份验证错误,因此服务器返回 JSON 格式的响应。
这是我的代码:
AFHTTPRequestOperation* op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[op setResponseSerializer:[AFJSONResponseSerializer serializer]]; // ??????
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSDictionary* result = (NSDictionary*) responseObject;
onSuccess((NSArray*) result);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
onFailure(error);
}];
[op start];
如您所见,我必须通过将 responseSerializer 设置为 [AFJSONResponseSerializer serializer] 来隐式设置预期的内容类型。因此,如果我得到其他东西,它会导致错误,即使我可能仍然希望在处理错误时解析响应的进程。
所以我的问题是,我是否应该只使用标准的 AFHTTPResponseSerializer,检查响应状态代码,然后手动处理响应主体(如 json、xml、html 图像等)?
最佳答案
使用 acceptableContentTypes
在序列化器上设置您想要的可接受的内容类型:
AFJSONResponseSerializer *serializer = [AFJSONResponseSerializer serializer];
serializer.acceptableContentTypes = [NSSet setWithArray:@[@"text/plain", @"text/html"]];
[op setResponseSerializer:serializer];
来自docs :
By default,
AFJSONSerializer
accepts the following MIME types, which includes the official standard, application/json, as well as other commonly-used types:application/json text/json
您不必使用 AFJSONResponseSerializer
,因为您可以创建自己的序列化程序,只要它符合 AFURLResponseSerialization
协议(protocol)。
如果您有 JSON
响应但有 XML
错误响应,您可以将 AFHTTPResponseSerializer
子类化并在其中进行您自己的处理。
你也可以使用 AFCompoundResponseSerializer
只需通过您提供的序列化程序即可解析不同的响应类型。
关于ios - 使用 AFNetworking/AFHTTPRequestOperation 处理意外的响应内容类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23254867/