进行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);

}

记录一下。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容