ios - 如何在使用 NSURLSession 时传递凭据

标签 ios objective-c nsurlsession

我正在尝试使用 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 方法。还有什么我必须做的吗?

最佳答案

HTTP Basic一般会需要一个realm on the protection space;这可能是它失败的地方。使用 curl -v 检查从服务器返回的身份验证质询 header 以找出它是什么。

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

关于ios - 如何在使用 NSURLSession 时传递凭据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19784837/

相关文章:

ios - iOS 11 弹出键盘时 UiTextfield 不会向上移动(在以前的版本上工作)

ios - 从被拒绝的证书中清除 XCode 缓存

objective-c - 为什么将任何选择器发送到 Nil 对象什么都不做,但将 "invalid"选择器发送到任何 NSObject 会引发异常?

ios - 如何更改 NSURLSession 的凭据

ios - 无法弹出 UIImagePickerController

ios - 应用程序不会在设备上显示第一个 View (也不会崩溃),但在模拟器中可以完美运行。还为设备加载不同的图标

c - 如何从 NSArray 生成 C vector 或数组?

objective-c - 为什么 Xcode 会自动创建带下划线的变量?

ios - 获取 URLSession.shared.dataTask 的 http 响应状态码

ios - 在URLSession:task:didCompleteWithError中重试失败的下载