Https的数据请求的证书设置 CFNetwork SSLHandshake failed (-9806)

来源:互联网 发布:数据传输线 编辑:程序博客网 时间:2024/06/05 16:30

对于https的网络请求很多人都比较头疼,不止iOS包括pc端和移动端的很多请求都离不开https

CFNetwork SSLHandshake failed (-9806)

error = Error Domain=NSURLErrorDomain Code=-1202 "The certificate for this server is invalid. You might be connecting to a server that is pretending to be “192.168.10.16” which could put your confidential information at risk." 

遇到以上错误的请举手,没错这就是臭名昭著的https请求出现的错误。归结原因证书原因。但是如何设置呢,你会发现百度一下子废物了。现在就从iOS原生的网络请求着手解决这一问题.

研究了一下NSURLConnection这个类会发现一下两个代理

- (BOOL)connection:(NSURLConnection*)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace*)protectionSpace

- (void)connection:(NSURLConnection*)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge*)challenge

没错,iOS本身提供了对于https请求证书的设置,就在代理方法里。现在ok了,只要解决了代理的设置就可以完成完整的https请求

首先做好数据请求的相关准备



接着设置证书权限问题


看一下控制台输出

2013-11-02 14:07:07.719 HttpsRequest[485:70b] didReceiveAuthenticationChallenge NSURLAuthenticationMethodServerTrust 0

2013-11-02 14:07:07.720 HttpsRequest[485:70b] get the whole response

表明证书确实已经设置完成,现在可以做数据请求了



这里用的是NSURLConnection的代理方法来执行数据接受,因为块方法没办法做证书相关的设置

现在看一下请求回来的数据

returnString = [{"id":"52707093fc8712d98a867bcd","title":"八达岭长城走一走","date":1383177600000,"createUser":{"id":"18638097289","username":"lisi"},"state":"0"},{"id":"52707063fc8712d98a867bcc","title":"雍和宫一日游","date":1385856000000,"createUser":{"id":"18638097289","username":"lisi"},"state":"0"},{"id":"5270700cfc8712d98a867bca","title":"雍和宫逛一逛","date":1388361600000,"createUser":{"id":"18638097289","username":"lisi"},"state":"0"},{"id":"52707047fc8712d98a867bcb","title":"香山一日游","date":1388448000000,"createUser":{"id":"18638097289","username":"lisi"},"state":"0"}]

到这里为止,https的数据请求证书问题已经得到了解决。要说一下的是很多人会用AFNetwork的第三方,因为这个框架也是对NSURLConnection的封装和扩展,github上有对此类问题的细致说明,可以看看。这里只解决方向问题,细节问题还有待各位自己研究
0 0
原创粉丝点击