首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >iOS中的NSURLConnection和基本HTTP身份验证

iOS中的NSURLConnection和基本HTTP身份验证
EN

Stack Overflow用户
提问于 2009-12-29 15:06:56
回答 8查看 89.1K关注 0票数 85

我需要用基本的Authentication调用一个初始GET HTTP request。这将是第一次将请求发送到服务器,并且我已经有了username & password,因此不需要来自服务器的授权质询。

第一个问题:

  1. 是否必须将NSURLConnection设置为同步才能执行基本身份验证?根据此post上的答案,如果您选择异步路由,似乎无法执行基本身份验证。
  2. 是否有人知道在不需要质询响应的情况下说明GET request上的基本身份验证的示例代码?Apple's documentation显示了一个示例,但仅在服务器向客户端发出质询请求之后。

我是SDK的网络部分的新手,我不确定我应该使用哪些其他类来使其工作。(我看到了NSURLCredential类,但它似乎只在客户端向服务器请求授权资源之后才与NSURLAuthenticationChallenge一起使用)。

EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2009-12-29 21:08:46

我使用MGTwitterEngine的异步连接,它在NSMutableURLRequest (theRequest)中设置授权,如下所示:

代码语言:javascript
复制
NSString *authStr = [NSString stringWithFormat:@"%@:%@", [self username], [self password]];
NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodingWithLineLength:80]];
[theRequest setValue:authValue forHTTPHeaderField:@"Authorization"];

我不认为这种方法需要经历挑战循环,但我可能错了

票数 132
EN

Stack Overflow用户

发布于 2011-07-25 17:39:52

即使问题已经得到回答,我也想提出解决方案,它不需要外部库,我在另一个线程中找到的:

代码语言:javascript
复制
// Setup NSURLConnection
NSURL *URL = [NSURL URLWithString:url];
NSURLRequest *request = [NSURLRequest requestWithURL:URL
                                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                                     timeoutInterval:30.0];

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

// NSURLConnection Delegates
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    if ([challenge previousFailureCount] == 0) {
        NSLog(@"received authentication challenge");
        NSURLCredential *newCredential = [NSURLCredential credentialWithUser:@"USER"
                                                                    password:@"PASSWORD"
                                                                 persistence:NSURLCredentialPersistenceForSession];
        NSLog(@"credential created");
        [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
        NSLog(@"responded to authentication challenge");    
    }
    else {
        NSLog(@"previous authentication failure");
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    ...
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    ...
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    ...
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    ...
}
票数 79
EN

Stack Overflow用户

发布于 2015-01-28 15:34:44

这是一个没有第三方参与的详细答案:

请在此处检查:

代码语言:javascript
复制
//username and password value
NSString *username = @“your_username”;
NSString *password = @“your_password”;

//HTTP Basic Authentication
NSString *authenticationString = [NSString stringWithFormat:@"%@:%@", username, password]];
NSData *authenticationData = [authenticationString dataUsingEncoding:NSASCIIStringEncoding];
NSString *authenticationValue = [authenticationData base64Encoding];

//Set up your request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.your-api.com/“]];

// Set your user login credentials
[request setValue:[NSString stringWithFormat:@"Basic %@", authenticationValue] forHTTPHeaderField:@"Authorization"];

// Send your request asynchronously
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *responseCode, NSData *responseData, NSError *responseError) {
      if ([responseData length] > 0 && responseError == nil){
            //logic here
      }else if ([responseData length] == 0 && responseError == nil){
             NSLog(@"data error: %@", responseError);
             UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"Error accessing the data" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil];
             [alert show];
             [alert release];
      }else if (responseError != nil && responseError.code == NSURLErrorTimedOut){
             NSLog(@"data timeout: %@”, NSURLErrorTimedOut);
             UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"connection timeout" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil];
             [alert show];
             [alert release];
      }else if (responseError != nil){
             NSLog(@"data download error: %@”,responseError);
             UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"data download error" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil];
             [alert show];
             [alert release];
      }
}]

请让我知道你对此的反馈。

谢谢

票数 13
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1973325

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档