我尝试读取邮件请求的回复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
发布评论