ios sendAsynchronousRequest重定向基本身份验证

时间:2012-11-09 19:40:19

标签: ios authentication redirect nsurlconnection

是否可以使用NSURLConnection sendAsynchronousRequest ,知道请求的网址会有重定向,所有请求也必须使用基本身份验证?

我收到以下错误:错误域= NSURLErrorDomain代码= -1012“操作无法完成。(NSURLErrorDomain错误-1012。)

我确实使用NSURLConnectionDelegate编写了一些代码并修改了重定向请求,以便在标题中添加基本身份验证功能。

所以我猜它与第二个请求中未设置的身份验证有关。与代理人相同,如果我没有在重定向请求中设置基本身份验证,那么事情就会因 HTTP 401 未经授权而失败

1 个答案:

答案 0 :(得分:0)

有可能我相信,正如我现在所做的那样,这是我的代码,诀窍是使用“Basic base64encodedmethod(username:password)”为“授权”设置标题

//SETUP URL
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://YOURURLHERE"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                   timeoutInterval:90.0];

//Get the username & password - then encode the values with Base64 (i googled for a library)
 NSString *userAndPassword = [NSString stringWithFormat:@"%@:%@",userName,password];
    NSString *encodedString = [userAndPassword base64EncodedString];

//Set the Authorization header which will now let your service calls pass basic authentication
    [request addValue:[NSString stringWithFormat:@"Basic %@",encodedString] forHTTPHeaderField:@"Authorization"];

//Setup a queue and call the async request - remember to do items in your block on the 
//main thread if it's for things like showing/hiding items as other threads will not run that code when you're expecting it

NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
//your code block here 
}];

我相信这会回答你的问题,现在我只需要找出如何删除该身份验证,以便我可以将用户注销,因为我正在构建一个安全的法律网站。任何帮助将不胜感激