ios - 如何从 AFNetworking 中的 POST 请求中读取一个简单的字符串(无 JSON)

标签 ios objective-c post afnetworking

我正在使用 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 的一部分。

最佳答案

您可以告诉 AFHTTPRequestOperationManagerAFHTTPSessionManager 如何处理响应,例如在调用 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/

相关文章:

objective-c - 从 NSWorkspace 获取 NSWindow 对象?

python - 找到在 Robinhood 上获取比特币价格的 api 调用

Python 代理不处理 POST 请求

javascript - 涉及 post json 调用的同步函数调用,其中一个函数应该在另一个函数成功后成功

ios - 从 TableView 中检索索引路径

ios - iOS 中用于交互元素的动态类型

ios - 如何使用 Swift 播放声音?

iphone - __IPHONE_OS_VERSION_MIN_REQUIRED 不返回部署目标?

ios - -[NSString writeToFile :] does not change the contents of the file

ios - 尝试从对象[1]插入nil对象