【问题标题】:How to do http basic aunthentication on iOS9?如何在 iOS 9 上进行 http 基本身份验证?
【发布时间】:2015-12-26 02:07:13
【问题描述】:

我一直在尝试通过 http 基本身份验证将我的 ios 应用程序连接到我的 restful web API,但我无法连接。这是我的代码:

let URL = NSURL(string:"https://devWebsvc1.whateverYolo.local:11201/api/webcall")
let theRequest = NSMutableURLRequest(URL:URL)
let session = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration())
theRequest.HTTPMethod = "POST"
theRequest.addValue("application/json", forHTTPHeaderField:"Content-Type")
theRequest.addValue("application/json", forHTTPHeaderField:"Accept")


let credential = NSURLCredential(user:"username", password:"password", persistence: NSURLCredentialPersistence.ForSession)
let protectionSpace = NSURLProtectionSpace(Host: URL?.host)!, port:11201, 'protocol': URL?.scheme, realm: nil, authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
let credentialStorage = NSURLCredentialStorage.sharedCredentialStorage()
credentialStorage.setDefaultCredential(credential,forProtectionSpace:protectionSpace)
theSession.configuration.URLCredentialsStorage = credentialStorage

let task = theSession.dataTaskWithRequest(theRequest, completionHandler : {data, response, error -> Void in 
if error != nil
{print("\(error)")}})

错误信息是:-

Optional(Error Domain=NSURLErrorDomain Code=-1200 "发生 SSL 错误,无法与服务器建立安全连接。" UserInfo={NSURLErrorFailingURLPeerTrustErrorKey=, NSLocalizedRecoverySuggestion=您是否仍要连接服务器?, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9802, NSErrorPeerCertificateChainKey={type = immutable, count = 1, values = ( 0: )}, NSUnderlyingError=0x7fe023520170 {错误域=kCFErrorDomainCFNetwork 代码=-1200 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, kCFStreamPropertySSLPeerTrust=, _kCFNetworkCFStreamSSLErrorOriginalValue=-9802, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9802, = imperableCertificates , 计数 = 1, 值 = ( 0: )}}}, NSLocalizedDescription=发生 SSL 错误,无法与服务器建立安全连接。, NSErrorFailingURLKey=https://devwebsvc1.whateverYolo.local:11201/api/Device, NSErrorFailingURLStringKey=https://devwebsvc1.whateverYolo.local:11201/api/Device, NSErrorClientCertificateStateKey=0})

你们知道可能是什么错误吗?任何帮助表示赞赏。顺便说一句,我正在使用 xcode 7。

【问题讨论】:

  • 您的服务器是否处理 TLS 1.2 安全协议?现在在 iOS 9 中是必需的。如果这是问题,您可以在此处寻找解决方案。 stackoverflow.com/a/30748166/1671729

标签: json ssl swift2 xcode7 basic-authentication


【解决方案1】:

错误可能在这一行:-

theRequest.addValue("application/json", forHTTPHeaderField:"Accept")

你应该去这个谷歌扩展并找到字段“接受”的值是什么

chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo/RestClient.html

添加您的网址、用户名和密码,然后点击提交,发现您的所有 Header Field 都是这样正确的,请检查 Content-Type 的值

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-27
    • 2015-09-07
    • 2013-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多