0

我正在尝试连接到 iOS 应用程序中的服务器。这是我的代码:

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{

    NSLog(@"This is happening");
    NSURLCredential *newCredential = [NSURLCredential credentialWithUser:@"user"
                                                                password:@"password"
                                                             persistence:NSURLCredentialPersistenceForSession];
    [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
int code = [httpResponse statusCode];
NSLog(@"%i",code);

}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", newStr);


}
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
NSLog(@"here...");

 return YES;

}

这是在 viewDidLoad 中:

NSString *url = @"http://example.com:9999/";
NSURL * URL = [NSURL URLWithString:url];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:URL];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

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

这是代表的标题:

<NSURLConnectionDelegate,NSURLConnectionDataDelegate>

没有调用 didReceiveAuthenticationChallenge,但调用了 didReceiveResponse 并打印“401”,并且 didReceiveData 返回页面上的文本“需要身份验证”。

didReceiveAuthenticationChallenge 从未被调用,canAuthenticateAgainstProtectionSpace 也从未被调用,因此我无法进行身份验证。我该如何补救?

4

2 回答 2

0

您必须在您的 url 中使用 https 而不是 http 才能调用此方法。

NSString *url = @"https://example.com:9999/";
NSURL * URL = [NSURL URLWithString:url];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:URL];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection self];
于 2013-07-25T15:01:40.710 回答
0

我想你缺少一个代表

NSURLAuthenticationChallengeSender

于 2013-11-28T09:28:20.517 回答