iOS:我如何接收HTTP 401而不是-1012 NSURLErrorUserCancelledAuthentication [英] iOS: How can i receive HTTP 401 instead of -1012 NSURLErrorUserCancelledAuthentication
问题描述
我遇到类似于以下链接中描述的问题。
I have a problem similar to the one described in the link below.
NSHTTPURLResponse statusCode返回零,应该是401
I使用 [NSURLConnection sendSynchronousRequest:returningResponse:error:]
从服务器获取数据。
I use [NSURLConnection sendSynchronousRequest:returningResponse:error:]
to get data from a server.
当NSURLConnection收到HTTP时代码401,它不会从NSURLErrorDomain返回任何代码为 -1012
的错误对象。 -1012
对应 NSURLErrorUserCancelledAuthentication
。由于我必须解析HTTP Header,我需要获取原始错误而不是NSURLConnection所做的。
When NSURLConnection receives the HTTP Code 401, it does not return anything but an error object with code -1012
from the NSURLErrorDomain. -1012
corresponds to NSURLErrorUserCancelledAuthentication
. Since I have to parse the HTTP Header I need to get the original error and not what NSURLConnection made out of it.
有没有办法接收原始的401 http数据包?
Is there a way to receive the original 401 http packet?
推荐答案
是的。停止使用同步API。如果您使用基于异步委托的API,那么您可以更好地控制连接。使用此API,除非在收到HTTP标头之前遇到错误,您将始终接收 -connection:didReceiveResponse:
,允许您访问HTTP标头字段(封装在 NSURLResponse
对象中)。如果您愿意,也可以使用相关的委托方法实现身份验证。
Yes. Stop using the synchronous API. If you use the asynchronous delegate-based API then you have a lot more control over the connection. With this API, except in cases where an error is encountered before the HTTP header is received, you will always receive -connection:didReceiveResponse:
, which gives you access to the HTTP header fields (encapsulated in an NSURLResponse
object). You can also implement authentication using the relevant delegate methods if you are so inclined.
这篇关于iOS:我如何接收HTTP 401而不是-1012 NSURLErrorUserCancelledAuthentication的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!