我有一個Web API,如果一切正常,對於特定請求返回狀態碼200,如果用戶未根據授權令牌登錄,則返回401。如果響應狀態爲200,則一切正常,但如果響應狀態爲401,則返回連接錯誤,代碼爲-1012,響應爲零時似乎無法正常工作。NSURLConnection返回錯誤,而不是響應401
所以,下面的代碼:
[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以及以下標題(複製f rom 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狀態之後?它可以出現在另一種類型的請求之後嗎?
正如我所見,連接:didReceiveAuthenticationChallenge:已被棄用爲OS.x(可能在未來的iOS也是如此),我認爲連接:willSendRequestForAuthenticationChallenge:也會幫助我,對不對? 那我在哪裏得到答案? – 2015-04-01 14:02:57
將得到連接的響應:didReceiveResponse:,我猜。 – 2015-04-01 14:09:31
您可以使用connection:didReceiveResponse,connection:didReceiveData和connectionDidFinishLoading。所以,你也需要實現NSURLConnectionDataDelegate協議。 – 2015-04-01 14:15:52