【问题标题】:How can I pass credentials while using NSURLSession如何在使用 NSURLSession 时传递凭据
【发布时间】:2013-12-25 03:38:42
【问题描述】:

我正在尝试使用 utorrent webui 登录到我自己的计算机。

目前我正在使用以下代码:

- (void)login
{
NSURL *feedsURL = [NSURL URLWithString:@"http://localhost:12345/"];

NSString *user = @"username";
NSString *password = @"password";
NSURLCredential *defaultCredential = [NSURLCredential credentialWithUser:user password:password persistence:NSURLCredentialPersistencePermanent];

NSString *host = [feedsURL host];
NSInteger port = [[feedsURL port] integerValue];
NSString *protocol = [feedsURL scheme];
NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc] initWithHost:host port:port protocol:protocol realm:nil authenticationMethod:NSURLAuthenticationMethodHTTPBasic];

NSURLCredentialStorage *credentials = [NSURLCredentialStorage sharedCredentialStorage];
[credentials setDefaultCredential:defaultCredential forProtectionSpace:protectionSpace];

NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
[config setURLCredentialStorage:credentials];

NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:nil delegateQueue:nil];
[[session dataTaskWithURL:feedsURL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if (!error) {
        NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;
        if (httpResp.statusCode == 200) {
            NSLog(@"Woo! everything is working");
        } else {
            NSLog(@"Hrmmm... error %@ occured", error);
        }
    } else {
        NSLog(@"Hrmmm... error %@ occured", error);
    }

}] resume];

我在使用桌面网络浏览器时可以正常查看该页面,但是在我的应用程序上它总是返回 401 错误(未授权)。

我猜这是因为没有使用凭据?如果是这样,正确的使用方法是什么?也没有调用 NSURLSessionDelegate 方法。我还有什么需要做的吗?

【问题讨论】:

  • 你检查你的端口号了吗?我尝试了您的代码并且得到了 401,直到强制端口 80 用于保护空间。在您的示例中,从 URL 检索到的端口号为 0。使用端口 80 我从 URL 获取数据!

标签: ios objective-c nsurlsession


【解决方案1】:

HTTP Basic 通常需要在保护空间上设置一个领域;这可能是它失败的地方。使用curl -v 检查从服务器返回的身份验证质询标头以找出它是什么。

除此之外,您列出的代码应该可以工作 - 我刚刚实现了一些非常相似的东西,并且凭据正在正确传递。我也遇到了委托身份验证质询方法未被调用的问题。

【讨论】:

    【解决方案2】:

    尝试将localhost替换为带有端口的计算机IP地址

    【讨论】:

      猜你喜欢
      • 2015-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-25
      • 2015-03-07
      • 1970-01-01
      • 1970-01-01
      • 2014-08-03
      相关资源
      最近更新 更多