如何从Webserver获取cookie并在iOS应用程序中维护它? [英] How to get cookie from Webserver and maintain it in iOS app?

查看:286
本文介绍了如何从Webserver获取cookie并在iOS应用程序中维护它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 http:// mycompany获取抓取JSON .com / page1 ... http://mycompany.com/page2 ...在Web服务器端,需要初始登录 http://mycompany.com/login ,然后为用户维护Cookie。我如何得到这种行为与NSURLConnection,而不必要求每次登录?这里是使用NSURLCredential存储的非工作代码。我需要在登录时从webservice获取cookie,然后将其与后续请求一起发送?

I would like to to get fetch JSON from http://mycompany.com/page1...http://mycompany.com/page2... On the the webserver side, it requires initial login http://mycompany.com/login, and after that a cookie is maintained for the user. How do I get this behavior with NSURLConnection without having to ask for login every time? Here is the non-working code using NSURLCredential Storage. Do I need to get the cookie from webservice at loging and then send it along with later requests? I struggled with this for some time, So can you please clarify your answer.

- (IBAction)getJSON:(id)sender
{


NSURLCredential *credential = [NSURLCredential credentialWithUser:@"user"
                                                         password:@"pass"
                                                          persistence:NSURLCredentialPersistenceForSession];

NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc]
                                         initWithHost:@"myCompany.com"
                                         port:0
                                         protocol:@"http"
                                         realm:nil
                                         authenticationMethod:nil];

[[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:credential
                                                    forProtectionSpace:protectionSpace];


//////////GET JSON//////////////

NSError *error;
NSURL *url = [NSURL URLWithString:@"http://mycompany.com.jsonpage1"];
 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}

 //I am NOT getting JSON in this delegate
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

NSString *responseString = [[NSString alloc] initWithData:responseData    encoding:NSUTF8StringEncoding];

NSLog(@"%@",responseString);

}


推荐答案

请参阅管理HTTP Cookie iPhone

设置cookie:

...使用cookie属性设置字典, / p>

... set dictionary with cookie properties, then:

NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:[NSDictionary dictionaryWithObjects:object forKeys:keys]];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];

但请记住,会话Cookie可以在您的服务器上过期

but keep in mind that session cookies can expire on your server

这篇关于如何从Webserver获取cookie并在iOS应用程序中维护它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆