如何使用Alamofire读取响应cookie [英] How to read response cookies using Alamofire

查看:343
本文介绍了如何使用Alamofire读取响应cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试读取邮件请求的回复Cookie,如下面的Postman所做。



我现在尝试没有成功的方式是

  var cfg = NSURLSessionConfiguration.defaultSessionConfiguration()
var cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage()
cfg.HTTPCookieStorage = cookies
cfg.HTTPCookieAcceptPolicy = NSHTTPCookieAcceptPolicy.Always

var mgr = Alamofire。 Manager(配置:cfg)


mgr.request(.POST,http://example.com/LoginLocalClient,parameters:parameters).responseJSON {response in

print(response.response!.allHeaderFields)

print(NSHTTPCookieStorage.sharedHTTPCookieStorage()。cookies)
}

第一个print语句包含没有cookie的10个标题字段,第二个包含空数组。



任何想法?

解决方案

该响应使用 NSHTTPCookie cookiesWithResponseHeaderFields(_:forURL :) method。这里有一个快速示例:

  func fetchTheCookies(){
let parameters:[String:AnyObject] = [:]

Alamofire.request(.POST,http://example.com/LoginLocalClient,parameters:parameters).responseJSON {response in
if let
headerFields = response。 response?.allHeaderFields as? [String:String],
URL = response.request?.URL
{
let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(headerFields,forURL:URL)
print $ b}
}
}

正在尝试的所有配置自定义做不会有任何影响。您设置的值已经是所有默认值。


I am trying to read the response cookies for a post request, as done by Postman below

The way I am trying without success right now is

    var cfg = NSURLSessionConfiguration.defaultSessionConfiguration()
    var cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage()
    cfg.HTTPCookieStorage = cookies
    cfg.HTTPCookieAcceptPolicy = NSHTTPCookieAcceptPolicy.Always

    var mgr = Alamofire.Manager(configuration: cfg)


    mgr.request(.POST, "http://example.com/LoginLocalClient", parameters: parameters).responseJSON { response in

                print(response.response!.allHeaderFields)

                print(NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies)
}

The first print statement contains the 10 header fields without the cookies, the second one contains an empty array.

Any ideas?

解决方案

You need to extract the cookies from the response using the NSHTTPCookie cookiesWithResponseHeaderFields(_:forURL:) method. Here's a quick example:

func fetchTheCookies() {
    let parameters: [String: AnyObject] = [:]

    Alamofire.request(.POST, "http://example.com/LoginLocalClient", parameters: parameters).responseJSON { response in
        if let
            headerFields = response.response?.allHeaderFields as? [String: String],
            URL = response.request?.URL
        {
            let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(headerFields, forURL: URL)
            print(cookies)
        }
    }
}

All the configuration customization you are attempting to do won't have any affect. The values you have set are already all the defaults.

这篇关于如何使用Alamofire读取响应cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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