从NSHTTPURLResponse获取cookie [英] Get cookies from NSHTTPURLResponse

查看:296
本文介绍了从NSHTTPURLResponse获取cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常奇怪的问题,我正在请求一个URL,我想从中获取cookie,我已经使用这种方式来获取cookie:

I've an extremely weird problem, I'm requesting a URL and I want to get the cookies from it, I've used this way to get the cookies:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response;
    NSDictionary *fields = [HTTPResponse allHeaderFields];
    NSString *cookie = [fields valueForKey:"Set-Cookie"];
}

但是cookie不完整,缺少一些字段,我已经在PostMan上进行了检查,所有cookie都在那里.

BUT the cookies is not complete, there is some field is missing, I've checked it on PostMan, all the cookies is there.

在启动NSURLRequest时,我也使用了此方法.

I've used also this method when initiating the NSURLRequest.

[request setHTTPShouldHandleCookies:YES];

问题出在哪里?

注意:此问题在iOS上存在,我有一个android版本,它可以正常工作,并且所有cookie都在那里.

推荐答案

@ biloshkurskyi.ss的答案是正确的.

@biloshkurskyi.ss answer is spot on.

我花了半天的时间来找出为什么我的一些cookie没有出现在我的response.allHeaderFields上,但在iOS上却存在(使用相同的服务).

I spent half a day trying to find out why some of my cookies were not appearing in my response.allHeaderFields on iOS but it was there on Android (using the same service).

原因是因为某些cookie事先被提取并存储在共享cookie存储中.它们不会出现在allHeaderFields中.

The reason is because some cookies are extracted in advance and stored in the shared cookie store. They will not appear in allHeaderFields.

如果有人需要,这里是答案的快速3版本:

Here's the swift 3 version of the answer if anyone needs it:

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()

这篇关于从NSHTTPURLResponse获取cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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