Cookie未与NSMutableURLRequest一起发送

时间:2012-12-02 17:59:41

标签: cookies nsurlconnection nsurlrequest nsmutableurlrequest nshttpcookie

首先,应用程序会打开UIWebView到我网站上的登录页面,成功登录后,webview将被关闭。有一个我需要请求的URL会返回一个非常小的json数据。如果我使用webview启动此URL,则会返回正确的数据,因此假设登录会话仍处于活动状态(如果不存在,则会再次重定向到登录页面)

我需要在另一个视图中返回数据,而不是webview,因此我需要使用NSURLRequest来访问它。抓取stackoverflow一个晚上后,我有以下内容:

NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:
                          [cookieJar cookies]];
[request setAllHTTPHeaderFields:headers];

NSError * e;
NSData  *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&e];

在检查返回的数据时,包括登录页面源而不是预期的json数据,我可以得出结论,cookie没有发送,需要建议。

编辑:我输出了[request allHTTPHeaderField]并显示NSHTTPCookieStorage中的所有可用cookie都已附加到请求中。所以...我真的失去了我应该如何继续下去。

1 个答案:

答案 0 :(得分:1)

您无需明确设置Cookie。 NSURLConnection会自动为您完成此操作。

您是否在网络视图关闭后尝试打印出Cookie?

  [[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

    NSLog(@"%@", obj);
  }];