一、过路由器验证即UIWebView打开带BASIC验证的网页
1,需要引入的协议头文件
UIWebViewDelegate,NSURLConnectionDelegate,NSURLConnectionDataDelegate
2,_webView一定要设置loadRequest否则不会调用UIWebView的delegate方法,就无法做后续的认证工作
_webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
_webView.delegate = self;
[_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]]];
[self.view addSubview:_webView];
3,
//uiwebview发请求的时候就会调用此方法
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
{
NSLog(@"Did start loading: %@ auth:%d", [[request URL] absoluteString], _authed);
if (!_authed) {
_authed = NO;
/* pretty sure i'm leaking here, leave me alone... i just happen to leak sometimes */
[[NSURLConnection alloc] initWithRequest:request delegate:self];
return NO;
}
return YES;
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
{
NSLog(@"got auth challange");
if ([challenge previousFailureCount] == 0) {
_authed = YES;
/* SET YOUR credentials, i'm just hard coding them in, tweak as necessary */
[[challenge sender] useCredential:[NSURLCredential credentialWithUser:@"admin" password:@"admin" persistence:NSURLCredentialPersistencePermanent] forAuthenticationChallenge:challenge];
} else {
[[challenge sender] cancelAuthenticationChallenge:challenge];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
{
NSLog(@"received response via nsurlconnection");
/** THIS IS WHERE YOU SET MAKE THE NEW REQUEST TO UIWebView, which will use the new saved auth info **/
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://192.168.1.1"]];
[_webView loadRequest:urlRequest];
}