如何使用Alamofire读取响应cookie

编程入门 行业动态 更新时间:2024-10-26 09:20:50
本文介绍了如何使用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,example/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,example/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, "example/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, "example/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

本文发布于:2023-11-26 02:00:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632196.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   Alamofire   cookie

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!