我已经参考了许多关于我的问题的帖子。以下是我提到的链接,
-
如何在Swift 中进行HTTP请求+基本身份验证
-
https://developer.apple.com/forums/thread/68809
-
使用基本身份验证发出http请求
-
https://github.com/Alamofire/Alamofire/issues/32
swift 5/XCode 12版本中的基本身份验证失败。我在xcode,中得到以下错误
2021-07-08 15:28:32.693835+0200 App[43664:810014] Connection 1: encountered error(3:-9816)
2021-07-08 15:33:33.042464+0200 App[43664:821863] Connection 2: received failure notification
2021-07-08 15:33:33.042685+0200 App[43664:821863] Connection 2: failed to connect 3:-9816, reason -1
以下是我正在使用的代码(我正在使用urlsession(,
var mhUrlRequest = URLRequest(url: mhURL)
let userPasswordData = "username:password".data(using: .utf8)
let base64EncodedCredential = userPasswordData!.base64EncodedString(options: Data.Base64EncodingOptions.init(rawValue: 0))
let authString = "Basic (base64EncodedCredential)"
mhUrlRequest.setValue(authString, forHTTPHeaderField: "Authorization")
我甚至尝试了下面的代码
let config = URLSessionConfiguration.default
config.httpAdditionalHeaders = ["Authorization" : authString]
但这些似乎都不适合我。
将凭据转换为base64并不是更好的方法。试试这些代码
let url = "your_url"
let usu_pass = "username:password"
var authData = (usu_pass.data(using: .utf8)?.base64EncodedString())!
let url = URL(string:url)
let header = [
"content-type" : "text/xml",
"Authorization" : "Basic " + authData
]
var request = URLRequest(url: url!)
request.allHTTPHeaderFields = header
request.httpMethod = "POST"
...