我正在对一个服务器进行post调用,但我一直收到服务器证书无效的错误,所以经过研究,我发现我必须使用身份验证质询来信任服务器。(我打印身份验证挑战以确保它确实如此)但是调用的其余部分没有通过,我无法从我的服务器上取回信息,身份验证挑战之后什么都没有发生,通常我希望返回数据,但是什么也没发生,我的urlsessiondatadelegates也没有被调用(用break检查)。
有人能指出为什么会这样吗?代码:
var request = URLRequest(url: URL(string: "https://45.56.105.97:7915/search-v2")!)
request.httpMethod = "POST"
request.addValue("Basic ***********", forHTTPHeaderField: "Authorization")
let task = URLSession(configuration: .default, delegate: self, delegateQueue: OperationQueue.main)
task.dataTask(with: request) { (data, response, error) in
print(error)
print(data)
if let responseData = NSString(data: data!, encoding: String.Encoding.utf8.rawValue){
print("data: \(responseData)")
self.parseXML(data!)
}
}.resume()
委托方法:
func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
print("did autherntcationchallenge = \(challenge.protectionSpace.authenticationMethod)")
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
print("send credential Server Trust")
let credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
challenge.sender!.use(credential, for: challenge)
}else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPBasic{
print("send credential HTTP Basic")
let defaultCredentials: URLCredential = URLCredential(user: "username", password: "password", persistence:URLCredential.Persistence.forSession)
challenge.sender!.use(defaultCredentials, for: challenge)
}else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodNTLM{
print("send credential NTLM")
} else{
challenge.sender!.performDefaultHandling!(for: challenge)
}
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
print("Data received: \(data)")
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
print("Response received: \(response)")
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
print("something went wrong: \(error)")
}
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
print("rep: \(response)")
}
运行后,我得到的打印是:
身份验证质询= NSURL身份验证方法服务器信任是否发送凭据服务器信任
我也看到过关于我只能使用闭包或委托方法来检索数据的对话,我尝试了所有方法都没有成功。
**我也知道我不应该只是盲目地信任服务器,但我试图找出为什么我不能收到数据回来,我知道这有严重的安全缺陷。
2条答案
按热度按时间dldeef671#
有两个问题:
lzfw57am2#
在花了几乎一天的时间对我来说,它的工作后,确认协议
URLSessionTaskDelegate
沿着URLSessionDelegate
希望它能帮助面对同样的问题。