我正在使用 AFNetworking
通过 POST 与服务器通信,POST 响应包含我需要的信息的简单字符串。我正在使用以下代码:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST: MY_URL
parameters: MY_PARAMETERS
success:^(AFHTTPRequestOperation *operation, id responseObject) {
//do something
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//etc.
}];
但是,AFNetworking
似乎希望每个响应都采用 JSON 格式,因为我在执行请求时遇到此错误:
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=0x1566eb00 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
我如何告诉 AFNetworking
响应不是 JSON 对象是可以的?我见过一些涉及 AFHTTPClient
的东西,但它似乎不再是 AFNetworking
的一部分。
最佳答案
您可以告诉 AFHTTPRequestOperationManager
或 AFHTTPSessionManager
如何处理响应,例如在调用 POST
之前,您可以执行以下操作:
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
然后在您的success
block 中,您可以将NSData
转换为字符串:
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
话虽如此,您可能想考虑将您的 Web 服务转换为返回 JSON 响应,因为这种方式更容易解析(并区分有效响应和某些服务器错误)。
关于ios - 如何从 AFNetworking 中的 POST 请求中读取一个简单的字符串(无 JSON),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21024352/