您的位置:首页 > 理论基础 > 计算机网络

ios下https代理访问证书问题

2015-01-22 13:44 477 查看
在ios下,需要打开https链接,但是如果其中使用了代理访问,则会被默认返回证书验证错误,无法正常访问

通常是在国内访问国外facebook的情况下

这是因为

https访问的时候,会验证一次证书,如果用了代理,证书验证的时候会被认为有风险,则会拒绝掉连接

也就是为了避免中间人攻击而做的限制

这里可以考虑先用NSURLConnection创建一个https连接,让本次针对目标地址的连接在验证时忽略证书,就可以保证之后的连接再也没证书验证问题了

NSString* strUrl = [NSString stringWithFormat:@https://graph.facebook.com/me];
NSURLRequest* reqUrl = [NSURLRequest requestWithURL:[NSURL URLWithString:strUrl]];
NSURLConnection* conn = [NSURLConnection connectionWithRequest:reqUrl delegate:self];
[conn start];

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"connection didFailWithError result: %@", error);
}
- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection
{
return NO;
}

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{

//第一次验证通过,之后取消验证

if ([challenge previousFailureCount] ==0)

{
NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}
else
{
[[challenge sender] cancelAuthenticationChallenge:challenge];
}
}

// Deprecated authentication delegates.
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

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

//第一次验证通过,之后取消验证
if ([challenge previousFailureCount] ==0)

{
NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];    }
else
{
[[challenge sender] cancelAuthenticationChallenge:challenge];
}
}
- (void)connection:(NSURLConnection *)connection didCancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//做你需要做的事情

}


不过这个最好看看最新的sdk支不支持了。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: