我正在尝试连接到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,所以我无法进行身份验证。我该如何解决这个问题?
答案 0 :(得分:0)
您必须在网址中使用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];
答案 1 :(得分:0)
我认为你错过了一个代表
NSURLAuthenticationChallengeSender