gpt4 book ai didi

iphone - 如何连接到需要用户名和密码的网站

转载 作者:行者123 更新时间:2023-11-28 20:46:51 26 4
gpt4 key购买 nike

我有一个基本问题,我希望有一个我错过的简单答案。基本前提是我要连接到一个网站并下载一些 JSON 数据。我使用的是 Stig Brautaset 提供的框架,教程效果非常好。

我的问题是我要连接的网站采用格式,用户名和密码对于我的应用程序是固定的,因此用户永远不会输入它们。

curl -u username:password http://website.com/page

如何将 url 和密码传递给 NSURLConnection

它不一定是 NSURLConnection,它似乎是最好的选择。

我已经查看了 AdvancedUrlConnections 示例,但它似乎过于复杂并且相当陈旧。在网络上搜索也好不到哪里去。我希望你们中的一个人可以说只需设置这 2 个属性,然后当然是适当的侮辱......

最佳答案

NSURLConnection 会工作得很好。正如在另一个答案中指出的那样,实现 didReceiveAuthenticationChallenge 回调非常容易。

- (void) someMethod
{
NSURLRequest* request = [[NSURLRequest alloc]
initWithURL:[NSURL urlWithString:@"someURL"]

NSURLConnection* connection = [[NSURLConnection alloc]
initWithRequest:request delegate:self];

[connection release];
[request release];
}

这一切都非常简单。所有魔法都在 NSURLConnection 的委托(delegate)方法中发生:

这是您处理凭据质询的地方。我硬编码了一个假的用户名和密码来演示它是如何工作的。我个人有一个单独的委托(delegate)对象来处理挑战。请记住,连接将处于空闲状态,直到您响应它或直到连接超时。

- (void) connection:(NSURLConnection *)connection 
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
// Make sure to use the appropriate authentication method for the server to
// which you are connecting.
if ([[challenge protectionSpace] authenticationMethod] ==
NSURLAuthenticationMethodBasicAuth)
{
// This is very, very important to check. Depending on how your
// security policies are setup, you could lock your user out of his
// or her account by trying to use the wrong credentials too many
// times in a row.
if ([challenge previousFailureCount] > 0)
{
[[challenge sender] cancelAuthenticationChallenge:challenge];

UIAlertView* alert = [[UIAlertView alloc]
initWithTitle:@"Invalid Credentials"
message:@"The credentials are invalid."
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
else
{
[challenge useCredential:[NSURLCredential
credentialWithUser:@"someUser"
password:@"somePassword"
persistence:NSURLCredentialPersistenceForSession
forAuthenticationChallenge:challenge]];
}
}
else
{
// Do whatever you want here, for educational purposes,
// I'm just going to cancel the challenge
[[challenge sender] cancelAuthenticationChallenge:challenge];
}
}

您还需要为 NSURLConnection 实现这些其他方法:

//  So you know when it's done downloading
- (void) connectionDidFinishLoading:(NSURLConnection *)connection;
// In case of failure
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
// Gather the downloaded file data
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;

关于iphone - 如何连接到需要用户名和密码的网站,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5252506/

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