gpt4 book ai didi

http - UIWebView 和 HTTP Basic Auth 的问题

转载 作者:可可西里 更新时间:2023-11-01 16:38:04 24 4
gpt4 key购买 nike

我在网上搜索了如何在 uiwebview 中进行基本的 http 身份验证。我已经尝试了所有方法,但无论我做什么,结果都不一致。有时 auth 有效,有时无效。这让我难以自拔,我希望得到一些帮助!

这是相关代码。我总是遇到身份验证挑战,但 webview 并不总是加载(我基本上超时等待 webViewDidFinishLoad - 没有错误)。有什么想法吗?

/*
Load a webview
*/
- (void)loadWebView
{
NSLog(@"loading webview");
if( _webView == NULL ){
// UIWebView initialization
_webView = [[UIWebView alloc] init];
_webView.hidden = TRUE;
}

// set up webview request
NSURL *url = [NSURL URLWithString:BASE_URL];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:30];

// load the request
[_webView setDelegate:self];
[_webView loadRequest:request];

// add ourselves as delegate to connection events so we can authenticate
(void)[NSURLConnection connectionWithRequest:request delegate:self];
}


/**
authenticates against HTTP basic authorization
*/
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
//receive a authenticate and challenge with the user credential
NSLog(@"got auth challenge. Authenticating...");
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodHTTPBasic] &&
[challenge previousFailureCount] == 0)
{
NSURLCredential *credentail = [NSURLCredential
credentialWithUser:AUTH_USERNAME
password:AUTH_PASS
persistence:NSURLCredentialPersistenceForSession];


[[challenge sender] useCredential:credentail forAuthenticationChallenge:challenge];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error Message" message:@"Invalid credentails" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
}
}

/**
store auth credentials
*/
- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection;
{
NSLog(@"using credential storage");
return YES;
}

最佳答案

你可以在url而不是请求头中传递认证请尝试代替 BASE_URL:

NSString* urlString = [NSString stringWithFormat:@"%@//%@:%@@%@",@"http:",userName,password,myUrl]

关于http - UIWebView 和 HTTP Basic Auth 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21017321/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com