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

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

问题描述:

我有一个基本问题,我希望有一个简单的答案,我错过了。基本前提是我要连接到一个网站并下载一些JSON数据。我正在使用Stig Brautaset提供的框架,该教程工作得很好。如何连接到需要用户名和密码的网站

我的问题是,我连接到的网站是格式和用户名和密码是固定的我的应用程序,所以用户将永远不会输入它们。

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

如何将网址和密码传递到NSURLConnection

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

我已经看过AdvancedUrlConnections样本,但它看起来过于复杂并且相当陈旧。在网上搜索并没有好多少。我希望你们中的一个人可以说只是设置这2个属性,然后是适当的侮辱当然...

的NSURLConnection的该-asBase64EncodedString方法会工作得很好。正如在另一个答案中指出的那样,执行回调函数很容易。

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

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

    [connection release]; 
    [request release]; 
} 

这是非常简单的。它在NSURLConnection的所有魔术发生的代表方法中:

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

- (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; 
+0

感谢您的帮助。我使用了大部分示例代码,但遇到了一些问题。首先是NSURLAuthenticationMethodBasicAuth无法识别,我刚刚评论说刚刚出来。另一个是forAuthenticationChallenge:挑战]] ;.括号出来了,但没有办法,我会得到这么远没有你的帮助,所以再次感谢。 – paulnug 2011-03-12 15:09:58

有几种可能性。

如果使用异步NSURLConnection,则将在连接的委托上调用方法-connection:didReceiveAuthenticationChallenge:。该方法的文档解释了如何处理它。这是AdvancedUrlConnections的用途,是的,这有点混乱。

更简单的方法是在创建连接时创建NSMutableURLRequest(而不是不可变的NSURLRequest)。这使您可以添加任意的HTTP标头。构建基本的认证报头是simple--像

NSMutableURLRequest *request = .... // details omitted 
NSString *username = // .... 
NSString *password = // .... 
NSData *authRawData = [[NSString stringWithFormat:@"%@:%@", username, password] dataUsingEncoding:NSUTF8StringEncoding]; 
NSString *authEncoded = [authRawData asBase64EncodedString]; 
[request setValue:[NSString stringWithFormat:@"Basic %@", authEncoded] forHTTPHeaderField:@"Authorization"]; 

以上使用包含在TouchFoundation

+0

强制性安全备注:请确保您的连接是SSL加密。 – 2011-03-10 01:23:48

+0

我尝试了以上,但从服务中得到错误。这不是一个SSL加密的视线,所以我认为这可能是问题。谢谢你的帮助。我现在更了解这个过程。 – paulnug 2011-03-12 15:12:10

+0

错误是好的,如果他们是信息。一个很好的错误信息会导致您找到解决方案。至少它不只是默默地失败。 – 2011-03-14 16:47:50