我正在使用NSURLConnection通过https进行身份验证,这很正常,但是当使用NSData下载文件时,我无法访问内容。如何通过经过身份验证的网址下载文件?
以下是我正在尝试阅读下载文件的内容(此处未包含验证码),服务器显示“用户未经授权”:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSFileManager *fileManager = [NSFileManager defaultManager];
// Attempt to open the file and write the downloaded data to it
if (![fileManager fileExistsAtPath:documentsDirectory2]) { //download path
[fileManager createFileAtPath:documentsDirectory2 contents:nil attributes:nil];
}
// Append data to end of file
NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:documentsDirectory2];
[fileHandle seekToEndOfFile];
[fileHandle writeData:data];
[fileHandle closeFile];
//data.txt exists, read me its content
NSArray *paths8 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory8 = [paths8 objectAtIndex:0];
NSString *filePath8 = [documentsDirectory8 stringByAppendingPathComponent:@"data.txt"];
NSString *content8 = [NSString stringWithContentsOfFile:filePath8 encoding:NSUTF8StringEncoding error:NULL];
NSLog(@"WHATS INSIDE DATA.TXT? =%@", content8);
[self.responseData appendData:data];
}
答案 0 :(得分:1)
在实施NSURLConnectionDelegate时,您需要使用NSURLCredential进行身份验证。
以下是一个例子:
-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
return YES;
}
-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
NSURLCredential *credential = [NSURLCredential credentialWithUser:username
password:passwd]
persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}