我在查看擁有自簽名證書並且還需要HTTP身份驗證的網站時遇到問題。目前我試圖通過使用How to display the Authentication Challenge in UIWebView?和UIWebView to view self signed websites (No private api, not NSURLConnection) - is it possible?作爲如何完成此操作的指南來實現它。我也嘗試使用繞過自簽名證書的私有API方法,但我無法找到指向它的鏈接。但是,私有API頭是:需要使用自簽名證書和http身份驗證查看網站
@interface NSURLRequest (DummyInterface)
+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString*)host;
+ (void)setAllowsAnyHTTPSCertificate:(BOOL)allow forHost:(NSString*)host;
@end
然後,我有這些作爲重要的功能:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
{
NSLog(@"Did start loading: %@ auth:%d", [[request URL] absoluteString], _authenticated);
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[URL host]];
_request=[NSURLRequest requestWithURL:URL];
if (!_authenticated) {
_authenticated = NO;
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[URL host]];
_urlConnection = [[NSURLConnection alloc] initWithRequest:_request delegate:self];
[_urlConnection start];
[mainWebView loadRequest:_request];
return NO;
}
return YES;
}
基本上調用NSURL連接日誌傳遞憑證。
#pragma mark - NURLConnection delegate
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
{
NSLog(@"WebController Got auth challange via NSURLConnection");
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[URL host]];
if ([challenge previousFailureCount] == 0)
{
_authenticated = YES;
NSURLCredential *credential = [NSURLCredential credentialWithUser:@"username"
password:@"password"
persistence:NSURLCredentialPersistenceForSession];
[challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
NSLog(@"credential created");
} else
{
NSLog(@"previous authentication failure");
[[challenge sender] cancelAuthenticationChallenge:challenge];
}
}
和
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
{
NSLog(@"WebController received response via NSURLConnection");
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSLog(@"remote url returned error %d %@",[httpResponse statusCode],[NSHTTPURLResponse localizedStringForStatusCode:[httpResponse statusCode]]);
NSLog(@"The response is =%@",response);
_authenticated = YES;
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[URL host]];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:URL];
[mainWebView loadRequest:urlRequest];
[_urlConnection cancel];
}