【问题标题】:Get status message from Response Headers under status code field从状态代码字段下的响应标头获取状态消息
【发布时间】:2013-10-29 12:56:44
【问题描述】:

我正在使用AFNetwokingAFHTTPClient 对象通过动词 PUT 访问 REST API。 我得到的响应是:状态 500 以及状态代码字段中响应标头字段中的自定义状态消息。

响应头域: 状态码:500 请检查您的货车号码,然后重试。

基本上问题是解析此状态消息。这是代码:

NSHTTPURLResponse *response;
NSMutableURLRequest *request = [httpClient requestWithMethod:PUT_CALL path:requestUrl parameters:params];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

响应对象没有获取此状态消息的 getter。当我尝试获取所有响应头字段时,我得到了所有键值对,除了消息也即将到来的状态代码字段。

【问题讨论】:

  • 为什么消息会出现在状态码标头中?
  • 我不确定放置消息和代码的标准方式是什么。但是我们正在访问的服务器正在以这种方式发送消息以及状态码。但有趣的是,我们还使用 HttpsURLConnection 类对象为 android 解析它,这个连接对象提供了一个 getter 来获取状态消息。我怎样才能在 iOS 上获得这个?

标签: ios rest afnetworking status-message


【解决方案1】:

您可以在委托方法-didRecieveResponse 中获取状态码:

    - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
       NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
       int code = [httpResponse statusCode];
    }

//Get the Body of the response
-   (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData{
    NSLog(@"String sent from server %@",[[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding]);

}

【讨论】:

  • 我可以成功获取状态码,实际问题也是获取消息。
  • 编辑我的答案,添加一个委托方法来获取响应正文。
猜你喜欢
  • 2015-06-08
  • 2019-04-11
  • 1970-01-01
  • 2018-03-14
  • 2020-01-10
  • 1970-01-01
  • 2016-05-23
  • 1970-01-01
  • 2011-07-17
相关资源
最近更新 更多