这里我尝试使用HTTP身份验证访问受保护的URL。但数据仍然无效。 代码:
{
NSURL *url = [NSURL URLWithString:@"http://mysecuredurl.com"];
NSString *userName =@"abc@v.com";
NSString *password =@"12345";
NSError *myError = nil;
NSMutableString *loginString = (NSMutableString*)[@"" stringByAppendingFormat:@"%@:%@", userName, password];
NSLog(@"loginstring=%@",loginString);
NSString *authHeader = [@"Basic " stringByAppendingFormat:@"%@", loginString];
NSLog(@"auth header =%@",authHeader);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url
cachePolicy: NSURLRequestReloadIgnoringCacheData
timeoutInterval: 3];
NSLog(@"request %@",request);
[request addValue:authHeader forHTTPHeaderField:@"Authorization"];
NSURLResponse *response;
NSData *data = [NSURLConnection
sendSynchronousRequest: request
returningResponse: &response
error: &myError];
NSLog(@"data %@",data);
NSLog(@"response %@",response);
NSString *result = [[NSString alloc]initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(@"result = %@",result);
}
数据和响应均为空。请帮我解决这个问题。我需要做些什么改变吗?谢谢。
答案 0 :(得分:0)
您的身份验证字符串需要进行base64编码。试试 -
NSData *userPasswordData = [[NSString stringWithFormat:@"%@:%@", userName, password] dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64EncodedCredential = [userPasswordData base64EncodedStringWithOptions:0];
NSString *authHeader= [NSString stringWithFormat:@"Basic %@", base64EncodedCredential]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url
cachePolicy: NSURLRequestReloadIgnoringCacheData
timeoutInterval: 3];
[request addValue:authHeader forHTTPHeaderField:@"Authorization"];