I am trying to read the response cookies for a post request, as done by Postman below
我正在尝试阅读帖子请求的响应cookie,如下面的Postman所做
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.
第一个print语句包含没有cookie的10个头字段,第二个包含一个空数组。
Any ideas?
有任何想法吗?
5 个解决方案
#1
21
You need to extract the cookies from the response using the NSHTTPCookie
cookiesWithResponseHeaderFields(_:forURL:) method. Here's a quick example:
您需要使用NSHTTPCookie cookiesWithResponseHeaderFields(_:forURL :)方法从响应中提取cookie。这是一个简单的例子:
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.
您尝试执行的所有配置自定义都不会产生任何影响。您设置的值已经是所有默认值。
#2
11
Please be advised that the accepted answer does not work if the cookies are not posted within the header response. Apparently, some cookies are extracted in advance and stored in the shared cookie store and will not appear with the response.
请注意,如果cookie未在标题响应中发布,则接受的答案不起作用。显然,一些cookie会提前提取并存储在共享cookie存储中,并且不会随响应一起显示。
You must use HTTPCookieStorage.shared.cookies
instead.
您必须使用HTTPCookieStorage.shared.cookies。
Swift 3:
斯威夫特3:
Alamofire.request(url, method: HTTPMethod.post, parameters: parameters).responseData { (responseObject) -> Void in
if let responseStatus = responseObject.response?.statusCode {
if responseStatus != 200 {
// error
} else {
// view all cookies
print(HTTPCookieStorage.shared.cookies!)
}
}
}
Credit goes to Travis M.
归功于Travis M.
#3
1
@lespommes
@lespommes
This is the only way I have received cookies. Now I can finally see Set-Cookie in a response:
这是我收到cookie的唯一方法。现在我终于可以在响应中看到Set-Cookie:
let parameters = ["postLogin": ["login": "mymail@gmail.com", "password": "myPassword"]]
let url = NSURL(string: "your-website-with-cookies.com")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(parameters, options: [])
Alamofire.request(request)
.responseJSON { response in
debugPrint(response)
if response.result.isSuccess {
...
}
}else if (response.result.isFailure){
...
}
}
#4
1
the above code was correct I have used in this way -
以上代码是正确的我用这种方式 -
var allCookies: [NSHTTPCookie]?
if let headerFields = aResponse.response?.allHeaderFields as? [String: String],
URL = aResponse.request?.URL {
allCookies = NSHTTPCookie.cookiesWithResponseHeaderFields(headerFields, forURL: URL)
for cookie in allCookies! {
print(cookie)
let name = cookie.name
if name == "nmSession" {
let value = cookie.value
print(value)
}
}
}
#5
1
If you just want to read all the cookies against the domain you are interacting with, you can get all cookies with this method.
如果您只想阅读与您正在交互的域的所有cookie,您可以使用此方法获取所有cookie。
let cookies = Alamofire.Manager.sharedInstance.session.configuration.HTTPCookieStorage?.cookiesForURL(NSURL(string: "mydomain.com")! )
It returns an optional array of NSHTTPCookie
items. (Swift 2.2 and Alamofire 3.4)
它返回NSHTTPCookie项的可选数组。 (Swift 2.2和Alamofire 3.4)
Swift 4.1:
let cookies = Alamofire.SessionManager.default.session.configuration.httpCookieStorage?.cookies(for: url)
#1
21
You need to extract the cookies from the response using the NSHTTPCookie
cookiesWithResponseHeaderFields(_:forURL:) method. Here's a quick example:
您需要使用NSHTTPCookie cookiesWithResponseHeaderFields(_:forURL :)方法从响应中提取cookie。这是一个简单的例子:
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.
您尝试执行的所有配置自定义都不会产生任何影响。您设置的值已经是所有默认值。
#2
11
Please be advised that the accepted answer does not work if the cookies are not posted within the header response. Apparently, some cookies are extracted in advance and stored in the shared cookie store and will not appear with the response.
请注意,如果cookie未在标题响应中发布,则接受的答案不起作用。显然,一些cookie会提前提取并存储在共享cookie存储中,并且不会随响应一起显示。
You must use HTTPCookieStorage.shared.cookies
instead.
您必须使用HTTPCookieStorage.shared.cookies。
Swift 3:
斯威夫特3:
Alamofire.request(url, method: HTTPMethod.post, parameters: parameters).responseData { (responseObject) -> Void in
if let responseStatus = responseObject.response?.statusCode {
if responseStatus != 200 {
// error
} else {
// view all cookies
print(HTTPCookieStorage.shared.cookies!)
}
}
}
Credit goes to Travis M.
归功于Travis M.
#3
1
@lespommes
@lespommes
This is the only way I have received cookies. Now I can finally see Set-Cookie in a response:
这是我收到cookie的唯一方法。现在我终于可以在响应中看到Set-Cookie:
let parameters = ["postLogin": ["login": "mymail@gmail.com", "password": "myPassword"]]
let url = NSURL(string: "your-website-with-cookies.com")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(parameters, options: [])
Alamofire.request(request)
.responseJSON { response in
debugPrint(response)
if response.result.isSuccess {
...
}
}else if (response.result.isFailure){
...
}
}
#4
1
the above code was correct I have used in this way -
以上代码是正确的我用这种方式 -
var allCookies: [NSHTTPCookie]?
if let headerFields = aResponse.response?.allHeaderFields as? [String: String],
URL = aResponse.request?.URL {
allCookies = NSHTTPCookie.cookiesWithResponseHeaderFields(headerFields, forURL: URL)
for cookie in allCookies! {
print(cookie)
let name = cookie.name
if name == "nmSession" {
let value = cookie.value
print(value)
}
}
}
#5
1
If you just want to read all the cookies against the domain you are interacting with, you can get all cookies with this method.
如果您只想阅读与您正在交互的域的所有cookie,您可以使用此方法获取所有cookie。
let cookies = Alamofire.Manager.sharedInstance.session.configuration.HTTPCookieStorage?.cookiesForURL(NSURL(string: "mydomain.com")! )
It returns an optional array of NSHTTPCookie
items. (Swift 2.2 and Alamofire 3.4)
它返回NSHTTPCookie项的可选数组。 (Swift 2.2和Alamofire 3.4)
Swift 4.1:
let cookies = Alamofire.SessionManager.default.session.configuration.httpCookieStorage?.cookies(for: url)