0

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

- (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也是如此,所以我无法进行身份验证。我该如何补救?

+0

是'canAuthenticateAgainstProtectionSpace'叫或不? – Nerkatel

+0

它没有被调用。 – DCIndieDev

回答

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]; 
+0

我应该用什么来代替? – DCIndieDev

+0

刚刚更新了我的答案。你应该使用https://而不是http:// –

+0

啊,我明白了。不幸的是,我连接的网站没有https设置,只有HTTP。有没有其他方式连接到普通的http? – DCIndieDev

0

我认为你缺少一个代表

NSURLAuthenticationChallengeSender