我正在开发报亭应用程序并使用 NSURLRequest 下载问题 Assets 。
NSArray *contents = [issue.tableOfContents objectForKey:kSNTableOfContentsContents];
NSHTTPCookie *cookie;
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSLog(@"HERE GO MY COOKIES");
for (cookie in [cookieJar cookies]) {
NSLog(@"%@", cookie);
}
for (NSDictionary *contentItem in contents) {
NSString *contentURL_string = [contentItem objectForKey:kSNTableOfContentsRemoteURL];
NSURL *contentURL = [NSURL URLWithString:contentURL_string];
NSString *fileName = [contentItem objectForKey:kSNTableOfContentsContentsURL];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:contentURL];
NKAssetDownload *asset = [newsstandIssue addAssetWithRequest:request];
[request release];
....
[asset downloadWithDelegate:self];
....
}
当执行第一个 for 循环时,我的 cookie 似乎在 NSHTTPCookieStorage 中,但是当发送实际请求时, header 中没有 cookie 信息。我使用 CharlesProxy 进行查找。任何人都可以提供一些建议可能导致此问题的原因吗?
最佳答案
来自 this thread ,魔法咒语似乎是:
NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:
[cookieJar cookies]];
[request setAllHTTPHeaderFields:headers];
(警告:未经测试的代码。)
这会将您的 cookie jar 转换为 cookie 数组,然后转换为 header 的 NSDictionary
,最后,将这些 header 装订到您的请求中。正如 Adam Shiemke 在问题勘误表中所链接的那样,这与手动操作相当,但在我看来要干净得多。
根据 the documentation ,您可能还想检查 HTTPShouldHandleCookies
以查看您的默认 cookie 策略是否被正确使用。
关于objective-c - NSURLRequest 不发送 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9946881/