iOS:我如何接收HTTP 401而不是-1012 NSURLErrorUserCancelledAuthentication

Tom*_*men 32 iphone http nsurlconnection ios

我有一个类似于下面链接中描述的问题.

NSHTTPURLResponse statusCode应为401时返回零

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

当NSURLConnection收到HTTP代码401时,除了带有-1012NSURLErrorDomain 代码的错误对象外,它不返回任何内容.-1012对应于NSURLErrorUserCancelledAuthentication.由于我必须解析HTTP Header,我需要获取原始错误而不是NSURLConnection所做的.

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

Lil*_*ard 19

是.停止使用同步API.如果您使用基于异步委托的API,那么您可以更好地控制连接.有了这个API,除了在接收到HTTP头之前遇到错误的情况下,你将永远得到-connection:didReceiveResponse:,这使您可以访问HTTP报头字段(封装在一个NSURLResponse对象).如果您愿意,也可以使用相关的委托方法实现身份验证.

  • 如果您使用iOS5 + [NSURLConnection sendAsynchronousRequest:queue:completionHandler:],这又会成为一个问题. (11认同)

Mar*_*tos 18

解决方法:

[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;
   }
Run Code Online (Sandbox Code Playgroud)

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

  • 更好的是:`if(error.code == kCFURLErrorUserCancelledAuthentication)statusCode = 401;` (11认同)

Mik*_*ill 11

我对这个帖子的"推荐"答案感到惊讶.

好吧,我相信使用异步版本的方法好,但它仍然没有解释为什么sendSynchronousRequest功能确实让你在一个变量返回的响应代码通过,但在某些情况下,它只是返回.

4年因为报告这个问题,我使用的XCode 6.2与iOS 8.2,而这个古老的错误仍然存在.

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

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

NSHTTPURLResponse *response = nil;
NSData *data = [ NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error ];
Run Code Online (Sandbox Code Playgroud)

.. response返回为nil(因此我无法测试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}
Run Code Online (Sandbox Code Playgroud)

并且该sendSynchronousRequest函数返回一个冗长的XML字符串,其中包含... well ... this ...

<?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>
Run Code Online (Sandbox Code Playgroud)

来吧Apple,修复你的bug ...