如何从AFNetworking中的POST请求中读取一个简单的字符串(No JSON) [英] How to read a simple string from a POST request in AFNetworking (No JSON)

查看:280
本文介绍了如何从AFNetworking中的POST请求中读取一个简单的字符串(No JSON)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 AFNetworking 通过POST与服务器通信,该响应使用包含我需要的信息的简单字符串进行响应。我正在使用以下代码:

I'm using AFNetworking to communicate with a server through POST that responds with a simple string containing the information I need. I'm using the following code:

    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格式,因为我在执行请求时遇到此错误:

However, it seems that AFNetworking expects every response to be in JSON format because I get this error when I execute my request:


错误域= NSCocoaErrorDomain代码= 3840操作无法执行是
完成。(Cocoa error 3840.)(JSON文本没有以数组或
对象和选项开头,以允许未设置片段。)UserInfo = 0x1566eb00
{NSDebugDescription = 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 的一部分。

How can I tell AFNetworking that it's OK that the response is not a JSON object? I've seen something involving AFHTTPClient, but it doesn't seem to be part of AFNetworking anymore.

推荐答案

您可以告诉 AFHTTPRequestOperationManager AFHTTPSessionManager 如何处理响应,例如在调用 POST 之前,您可以执行以下操作:

You can tell the AFHTTPRequestOperationManager or AFHTTPSessionManager how to handle the response, e.g. before calling POST, you can do the following:

manager.responseSerializer = [AFHTTPResponseSerializer serializer];

然后在成功块中,你可以将 NSData 转换为字符串:

Then in your success block, you can convert the NSData to a string:

NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];

话虽如此,您可能想要转换您的Web服务以返回JSON响应,因为它远更容易解析(并区分有效响应和某些服务器错误)。

Having said that, you might want to contemplate converting your web service to return JSON response, as it's far easier to parse that way (and differentiate between a valid response and some server error).

这篇关于如何从AFNetworking中的POST请求中读取一个简单的字符串(No JSON)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆