4

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

4

2 回答 2

1

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

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

于 2013-11-06T15:30:32.230 回答
0

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

于 2013-12-24T19:38:42.770 回答