【问题标题】:how to get responseString when JSON failed with AFJSONRequestOperation当 JSON 因 AFJSONRequestOperation 失败时如何获取 responseString
【发布时间】:2013-08-02 19:20:04
【问题描述】:

当服务器未能发送有效的 JSON 响应时,我很难获得 responseString(fe. php 回显一些临时变量或出现问题)。我正在使用来自AFNetwokingAFJSONRequestOperation,如下所示:

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
    success:^(NSURLRequest *request, NSHTTPURLResponse *response, id responseObject) {
        NSLog(@"object: %@", responseObject);
    }
    failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id responseString) {
        NSLog(@"failure: %@", responseString);
    }
];

responseString 是失败的情况总是nil。当我尝试阅读文档 (http://cocoadocs.org/docsets/AFNetworking/1.3.1/Classes/AFJSONRequestOperation.html#//api/name/JSONRequestOperationWithRequest:success:failure:) 时,我发现有人写到失败会得到三个参数(但实际上是四个,第四个始终为零)。在这种情况下,有什么简单的方法可以将响应作为字符串获取?

【问题讨论】:

  • 失败时你得到什么反应。
  • 响应对象指示的内容长度是多少?
  • 2013-08-02 21:06:12.250 app[44769:c07] responseCode:200,错误:操作无法完成。 (Cocoa 错误 3840。)(null)如何从响应中获取内容长度?
  • 也许有点跑题了,但是当我遇到这种情况时,我总是使用 cURL 来测试服务器请求并在终端中打印输出。这有助于我捕捉可能的回声或通知。

标签: ios objective-c afnetworking nshttpurlresponse


【解决方案1】:

如果responseStringnil,那么您要么没有从服务器收到任何数据,要么数据无法用于创建有效的NSString 对象。

根据您的Cocoa error 3840 的声音,这对应于NSJSONSerialization 错误,我的猜测是服务器确实发回了一个空响应。

【讨论】:

  • 不幸的是,您的答案并非全部正确,JSON 序列化失败,但响应不为空(我什至尝试在 web 服务中放入类似 print('something'); die(); 和 responseString总是 nil...)
  • @patryk 你如何检查回复?你在用curl吗?使用 Charles.app、Wireshark 或类似工具在模拟器中嗅探传入的 HTTP 流量?
  • 我正在使用 GraphicalHTTPClient(可在 appstore 中获得),其请求参数与 AFNetworking 调用相同。
  • @patryk 如果不嗅探流量,您就无法完全确定传出请求的具体细节。这不仅仅是参数:请求标头也很重要。我鼓励您使用更全面的工具来验证所有内容。
  • 在这种情况下 GraphicalHTTPClient 就足够了,因为我知道有一些响应(因为当我得到正确的 JSON 成功方法时会给出正确的对象并且当我键入 print('something') 来破坏请求时)失败方法中的 responseString 为空...)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-09
  • 1970-01-01
  • 2016-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-29
相关资源
最近更新 更多