我正在嘗試使用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