我有一个非常奇怪的问题,我请求一个URL,我想从其中获取cookie,我用这种方式获得了cookie:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response;
NSDictionary *fields = [HTTPResponse allHeaderFields];
NSString *cookie = [fields valueForKey:"Set-Cookie"];
}但是cookies还没有完成,缺少一些字段,我已经在PostMan上检查过了,所有的cookie都在那里。
在启动NSURLRequest时,我也使用了这种方法。
[request setHTTPShouldHandleCookies:YES];问题出在哪里?
注意:这个问题发生在iOS上,我有一个安卓版本,运行良好,所有的cookies都在那里。
发布于 2016-10-24 22:02:02
@biloshkurskyi.ss的回答是对的。
我花了半天的时间试图找出为什么我的一些饼干没有出现在我的response.allHeaderFields on iOS上,但它在Android上(使用相同的服务)。
原因是有些cookie是预先提取出来并存储在共享cookie存储中的。它们不会出现在allHeaderFields中。
如果有人需要的话,这里有一个快速3版本的答案:
let request = URLRequest(url: myWebServiceUrl)
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: {
(data, response, error) in
if let error = error {
print("ERROR: \(error)")
} else {
print("RESPONSE: \(response)")
if let data = data, let dataString = String(data: data, encoding: .utf8) {
print("DATA: " + dataString)
}
for cookie in HTTPCookieStorage.shared.cookies! {
print("EXTRACTED COOKIE: \(cookie)") //find your cookie here instead of httpUrlResponse.allHeaderFields
}
}
})
task.resume()发布于 2013-09-28 11:57:25
您是否尝试过遵循代码示例,它应该可以工作:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSArray *cookies =[[NSArray alloc]init];
cookies = [NSHTTPCookie
cookiesWithResponseHeaderFields:[response allHeaderFields]
forURL:[NSURL URLWithString:@""]]; // send to URL, return NSArray
}发布于 2013-11-27 21:29:42
试试下面的代码:
for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies])
{
NSLog(@"name: '%@'\n", [cookie name]);
NSLog(@"value: '%@'\n", [cookie value]);
NSLog(@"domain: '%@'\n", [cookie domain]);
NSLog(@"path: '%@'\n", [cookie path]);
}https://stackoverflow.com/questions/19066577
复制相似问题