进行https请求的时候报HTTP load failed (kCFStreamErrorDomainSSL, -9843)

问题是会有一个验证服务器证书的过程,如果不设置验证不过,请求就会报错。

URLSession的代理中有个- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task

didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge

completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * __nullable credential))completionHandler;方法,在这个方法中设置就好了。

具体代码如下:

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task

didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge

completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * __nullable credential))completionHandler {

// 判断是否是信任服务器证书

if(challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {

// 告诉服务器,客户端信任证书

NSLog(@"protectionSpace = %@",challenge.protectionSpace);

NSLog(@"host:%@ ,realm:%@,port:%ld,proxyType:%@",challenge.protectionSpace.host,challenge.protectionSpace.realm,(long)challenge.protectionSpace.port,challenge.protectionSpace.proxyType);

// 创建凭据对象

NSURLCredential *credntial = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];

// 通过completionHandler告诉服务器信任证书

completionHandler(NSURLSessionAuthChallengeUseCredential,credntial);

}

NSLog(@"protectionSpace = %@",challenge.protectionSpace);

}

记录一下。

你可能感兴趣的:(进行https请求的时候报HTTP load failed (kCFStreamErrorDomainSSL, -9843))