【问题标题】:iOS: How can i receive HTTP 401 instead of -1012 NSURLErrorUserCancelledAuthenticationiOS:我如何接收 HTTP 401 而不是 -1012 NSURLErrorUserCancelledAuthentication
【发布时间】:2011-04-24 04:12:01
【问题描述】:

我遇到了与以下链接中描述的问题类似的问题。

NSHTTPURLResponse statusCode is returning zero when it should be 401

我使用[NSURLConnection sendSynchronousRequest:returningResponse:error:] 从服务器获取数据。

当 NSURLConnection 接收到 HTTP 代码 401 时,它不会返回任何内容,而是返回来自 NSURLErrorDomain 的代码为 -1012 的错误对象。 -1012 对应于 NSURLErrorUserCancelledAuthentication。由于我必须解析 HTTP 标头,因此我需要获取原始错误,而不是 NSURLConnection 从中产生的错误。

有没有办法接收原始的401 http包?

【问题讨论】:

  • 我遇到了同样的问题。
  • 你研究过 ASIHTTPRequest 吗?
  • 如果可能的话,我宁愿坚持使用内置 API。 FWIW,检查NSError out-param for NSURLErrorUserCancelledAuthentication 工作正常。奇怪的是,当返回状态 401 时,NSURLResponse 输出参数为零。

标签: iphone http ios nsurlconnection


【解决方案1】:

是的。停止使用同步 API。如果您使用基于异步委托的 API,那么您可以更好地控制连接。使用此 API,除非在收到 HTTP 标头之前遇到错误,否则您将始终收到-connection:didReceiveResponse:,这使您可以访问 HTTP 标头字段(封装在 NSURLResponse目的)。如果您愿意,也可以使用相关的委托方法来实现身份验证。

【讨论】:

  • 使用委托消息进行身份验证是不必要的,尤其是因为凭据始终相同,并且对于我的应用程序中的每个请求都是必需的。所以我只是在第一次发送之前自己将身份验证标头添加到NSURLRequest。我只需要返回响应代码和可能的(非常短的)响应正文数据。这个特定的请求也是我的算法中的几个顺序步骤之一,并且以异步方式执行此操作会使该顺序变得不那么清晰。
  • 如果你打算使用 NSURLConnection,异步 API 是获取你想要的数据的唯一方法。您唯一的选择是使用 HTTP 的第三方实现。
  • 我会将其标记为答案...尽管将其设为异步会产生“开销”,但我认为从长远来看,您对流程的控制会得到回报,您仍然可以换行使它看起来同步的整个过程
  • 如果你使用iOS5+ [NSURLConnection sendAsynchronousRequest:queue:completionHandler:],这又会成为一个问题。
【解决方案2】:

解决方法:

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue new] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

NSHTTPURLResponse *aResponse = (NSHTTPURLResponse *)response;
int statusCodeResponse = aResponse.statusCode;

NSString *strError = [NSString stringWithFormat:@"%@", [connectionError description]];
if ([strError rangeOfString:@"Code=-1012"].location != NSNotFound) {
    statusCodeResponse = 401;
   }

不是最好的解决方案,但它有效!

【讨论】:

  • 更好:if (error.code == kCFURLErrorUserCancelledAuthentication) statusCode = 401;
  • 如何快速做到这一点?
  • 不应该是if (error.code == NSURLErrorUserCancelledAuthentication) ?
【解决方案3】:

我对这个帖子的“推荐”答案感到惊讶。

好吧,我确信使用异步版本方法更好,但它仍然无法解释为什么sendSynchronousRequest 函数确实允许您传入一个变量以返回响应代码,但在某些情况下,它只会返回 nil

自报告此问题以来已经 4 年,我正在使用 XCode 6.2 和 iOS 8.2,但这个古老的错误仍然存​​在。

当用户的用户名和密码不正确时,我的 Web 服务故意返回 401 错误。

当我的 iPhone 应用调用此服务时(使用错误的凭据)...

NSHTTPURLResponse *response = nil;
NSData *data = [ NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error ];

..response 返回为零(所以我无法测试 HTTP 响应 401),error 收到 -1012 消息,如下所示:

    Error Domain=NSURLErrorDomain Code=-1012 "The operation couldn’t be completed. (NSURLErrorDomain error -1012.)" 
    UserInfo=0x174869940 {NSErrorFailingURLStringKey=https://mywebservice.com/Service1.svc/getGroupInfo/6079, NSUnderlyingError=0x174e46030 
    "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1012.)",
NSErrorFailingURLKey=https://mywebservice.com/Service1.svc/getGroupInfo/6079}

sendSynchronousRequest 函数返回一个长长的 XML 字符串,其中包含……嗯……这个……

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Request Error</title>
    <style>BODY { color: #000000; background-color: white; font-family: Verdana; margin-left: 0px; margin-top: 0px; } #content { margin-left: 30px; font-size: .70em; padding-bottom: 2em; } A:link { color: #336699; font-weight: bold; text-decoration: underline; } A:visited { color: #6699cc; font-weight: bold; text-decoration: underline; } A:active { color: #336699; font-weight: bold; text-decoration: underline; } .heading1 { background-color: #003366; border-bottom: #336699 6px solid; color: #ffffff; font-family: Tahoma; font-size: 26px; font-weight: normal;margin: 0em 0em 10px -20px; padding-bottom: 8px; padding-left: 30px;padding-top: 16px;} pre { font-size:small; background-color: #e5e5cc; padding: 5px; font-family: Courier New; margin-top: 0px; border: 1px #f0f0e0 solid; white-space: pre-wrap; white-space: -pre-wrap; word-wrap: break-word; } table { border-collapse: collapse; border-spacing: 0px; font-family: Verdana;} table th { border-right: 2px white solid; border-bottom: 2px white solid; font-weight: bold; background-color: #cecf9c;} table td { border-right: 2px white solid; border-bottom: 2px white solid; background-color: #e5e5cc;}</style>
  </head>
  <body>
    <div id="content">
      <p class="heading1">Request Error</p>
      <p>The server encountered an error processing the request. The exception message is 'Access is denied.'. See server logs for more details. The exception stack trace is: </p>
      <p>   at System.ServiceModel.Dispatcher.AuthorizationBehavior.Authorize(MessageRpc&amp; rpc)
   at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc&amp; rpc)
   at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)</p>
    </div>
  </body>
</html>

来吧,苹果,修复你的错误......

【讨论】:

  • 在标题中查找空格
【解决方案4】:

其实很简单。现在确实,异步请求实际上是一个很好的帮手。但你必须记住,它只是一个帮手。 Http 只是一种网络协议,因此它不能与用户交互。换句话说,这两种情况实际上是相同的。

如果您不想使用异步助手,我建议您向用户显示一个登录对话框并重复您的请求,直到用户按下取消。

[编辑]

仅供参考,我个人更喜欢 curl。几乎在任何地方都像魅力一样工作;)

【讨论】:

    【解决方案5】:

    我遇到的问题是没有收到 401 Unauthorized 错误代码(得到零响应,也没有调用 didReceiveResponse 方法),而是收到 -999 取消错误。我在代码中犯的错误是: 在 didReceiveChallenge: 委托方法中,

    if (challenge.previousFailureCount == 0)
    {
        //handle certificate trust
        completionHandler (NSURLSessionAuthChallengeUseCredential, newCredential);
    }
    else
    {
        completionHandler (NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
    }
    

    NSURLSessionAuthChallengeCancelAuthenticationChallenge 导致 -999 错误并且没有获得 401 响应。 相反,当我使用 completionHandler (NSURLSessionAuthChallengePerformDefaultHandling, nil);我在 didReceiveResponse: 委托方法中收到了 401 响应。

    来自 iOS 文档https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/URLLoadingSystem/NSURLSessionConcepts/NSURLSessionConcepts.html 的注释,如果我们取消 urlsession,那么它将被报告为已取消,但不会作为响应的 401 错误。

    Note: NSURLSession does not report server errors through the error parameter. The only errors your delegate receives through the error parameter are client-side errors, such as being unable to resolve the hostname or connect to the host. The error codes are described in URL Loading System Error Codes.
    Server-side errors are reported through the HTTP status code in the NSHTTPURLResponse object. For more information, read the documentation for the NSHTTPURLResponse and NSURLResponse classes.
    

    【讨论】:

      猜你喜欢
      • 2018-02-14
      • 1970-01-01
      • 2018-11-04
      • 2019-04-19
      • 2013-03-09
      • 2020-02-13
      • 2017-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多