我正在尝试使用NSURLConnection
连接到http://cmis.demo.nuxeo.org/nuxeo/atom/cmis/。此演示Web服务是documented要求身份验证(登录:管理员/密码:管理员)。NSURLConnection不使用默认凭证
编辑:此Web服务现在发送身份验证质询,但当时并未提出问题。
此Web服务不发送一个验证挑战,所以我不能用connection:didReceiveAuthenticationChallenge:
委托方法。相反,我在共享凭据存储中设置了默认的NSURLCredential
。不幸的是,这个默认凭证不被NSURLConnection
使用。
这里是我的代码(使用ARC,在iOS 5测试):
@implementation ViewController
{
NSMutableData *responseData;
}
- (IBAction) connect:(id)sender
{
NSString *user = @"Administrator";
NSString *password = @"Administrator";
NSURL *nuxeoURL = [NSURL URLWithString:@"http://cmis.demo.nuxeo.org/nuxeo/atom/cmis/"];
NSURLCredential *credential = [NSURLCredential credentialWithUser:user password:password persistence:NSURLCredentialPersistenceForSession];
NSString *host = [nuxeoURL host];
NSNumber *port = [nuxeoURL port];
NSString *protocol = [nuxeoURL scheme];
NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc] initWithHost:host port:[port integerValue] protocol:protocol realm:nil authenticationMethod:NSURLAuthenticationMethodHTTPBasic];
[[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:credential forProtectionSpace:protectionSpace];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:nuxeoURL];
BOOL manuallyAddAuthorizationHeader = NO;
if (manuallyAddAuthorizationHeader)
{
NSData *authoritazion = [[NSString stringWithFormat:@"%@:%@", user, password] dataUsingEncoding:NSUTF8StringEncoding];
NSString *basic = [NSString stringWithFormat:@"Basic %@", [authoritazion performSelector:@selector(base64Encoding)]];
[request setValue:basic forHTTPHeaderField:@"Authorization"];
}
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
responseData = [NSMutableData data];
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"connectionDidFinishLoading:%@", connection);
NSLog(@"%@", [[NSString alloc] initWithData:responseData encoding:NSISOLatin1StringEncoding]);
}
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"connection:%@ didFailWithError:%@", connection, error);
}
@end
由于不使用默认的凭证,我收到的HTML(登录页)而不是XML。如果我将manuallyAddAuthorizationHeader
变量设置为YES
,那么授权将起作用,并且我会收到xml。
我的问题是:为什么NSURLConnection
不是自动使用默认的NSURLCredential
?
我使用'authenticationMethod:NSURLAuthenticationMethodHTTPBasic'显式创建了一个'NSURLProtectionSpace',所以我想现在要使用什么方法。 – 0xced 2012-02-21 18:03:07