我有一个 Web API,对于特定请求,如果一切正常,则返回状态代码 200;如果用户未根据授权令牌登录,则返回 401。如果响应状态为 200,则一切正常,但如果响应状态为 401,则似乎无法正常工作,返回代码为 -1012 的连接错误,而响应为零。
所以,下面的代码:
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog(@"%@", response);
NSLog(@"%@", connectionError);
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
int statusCode = (int)[httpResponse statusCode];
NSLog(@"response status code: %d", statusCode);
将显示
2015-04-01 15:58:18.511 MyProject[3618:694604] <NSHTTPURLResponse: 0x155facc0> { URL: *SOME_URL* } { status code: 200, headers {
"Access-Control-Allow-Headers" = "Content-Type, Accept, X-Requested-With";
"Access-Control-Allow-Methods" = "POST, GET, PUT, UPDATE, OPTIONS";
"Access-Control-Allow-Origin" = "*";
Connection = "keep-alive";
"Content-Type" = "application/json";
Date = "Wed, 01 Apr 2015 12:58:14 GMT";
Server = "Wildfly 8";
"Transfer-Encoding" = Identity;
"X-Powered-By" = "Undertow 1";
} }
2015-04-01 15:58:18.513 MyProject[3618:694604] (null)
2015-04-01 15:58:18.513 MyProject[3618:694604] response status code: 200
如果响应状态为200,而如果状态代码为401,我将得到:
2015-04-01 16:05:55.988 MyProject[3633:695836] (null)
2015-04-01 16:05:55.992 MyProject[3633:695836] Error Domain=NSURLErrorDomain Code=-1012 "The operation couldn’t be completed. (NSURLErrorDomain error -1012.)" UserInfo=0x146137c0 {NSErrorFailingURLKey=*SOME_URL*, NSErrorFailingURLStringKey=*SOME_URL*, NSUnderlyingError=0x1459e6d0 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1012.)"}
2015-04-01 16:05:55.992 MyProject[3633:695836] response status code: 0
如果我使用 Postman 或 Android 设备执行相同的请求,我将收到带有以下标头的状态代码 401(从 Postman 复制):
Connection → keep-alive
Content-Length → 30
Content-Type → application/json
Date → Wed, 01 Apr 2015 13:07:34 GMT
Server → Wildfly 8
X-Powered-By → Undertow 1
是否有任何修复或可能有一个库可以为我提供一些准确的响应状态?我搜索了一些有关 -1012 错误的信息,但找不到太多内容,而且我真的不想以此为基础。
编辑:经过一番研究后,我在 Appl 的文档中发现了以下声明:“如果需要身份验证才能下载请求,则必须将所需的凭据指定为 URL 的一部分。如果身份验证失败或缺少凭据,连接将尝试在没有凭据的情况下继续。"
但是我怎么知道这个错误是否会出现在 401 状态之后呢?它可以出现在其他类型的请求之后吗?