带有 cookie 的 Alamofire 请求 [英] Alamofire request with cookies
问题描述
我是初学者,我不知道如何使用 Alamofire 发出 .GET 请求(但它需要身份验证).我设法使用其他网络服务(登录)来做到这一点,因为它需要参数参数:
I'm beginner and I can't figure out how to make a .GET request (however it requires autenthication) with Alamofire. I managed to do this with other web service (login) because it takes parameters argument:
parameters = [
"username" : username
"password" : password
]
那么:
Alamofire.request(.POST, loginUrl, parameters: parameters).responseJSON { (request, response, data, error) -> Void in
//handling the response
}
在响应头中,我得到了一些信息:
In response header I get some information:
[Transfer-Encoding: Identity, Server: nginx/1.4.1, Content-Type: application/json, P3P: policyref="http://www.somewebpage.com", CP="NON DSP COR CURa TIA", Connection: keep-alive, Date: Sun, 08 Mar 2015 13:49:20 GMT, Vary: Accept-Encoding, Cookie, Set-Cookie: sessionid=5xeff47e65f674a4cc5b2d54f344304b; Domain=.somedomain.com; Path=/, tbauth=1; Domain=.somedomain.com; Path=/, Content-Encoding: gzip]
它的类型是 [NSObject : AnyObject]
我应该如何处理这些信息以将其存储在 NSURLDefaults 中并准备有效的请求参数 (cookie)?我需要所有字段还是只需要 Set-Cookie?
What should I do with that information to store it in NSURLDefaults and prepare valid request parameter (cookie)? Do I need all fields or just Set-Cookie?
我尝试手动设置参数:
parameters = [
"Cookie" : "sessionid=5xeff47e65f674a4cc5b2d54f344304b; Domain=.somedomain.com; Path=/, tbauth=1; Domain=.somedomain.com; Path=/"
]
但它确实返回错误 NSURLErrorDomain -1017 (NSURLErrorCannotParseResponse)
but it does return error NSURLErrorDomain -1017 (NSURLErrorCannotParseResponse)
感谢所有回复.
推荐答案
好的,两周后我才找到解决方案:
Ok, after 2 weeks I just found a solution:
let URL = NSURL(string: query)!
let mutableUrlRequest = NSMutableURLRequest(URL: URL)
mutableUrlRequest.HTTPMethod = "GET"
let prefs = NSUserDefaults.standardUserDefaults()
let cookie = prefs.valueForKey("COOKIE") as String
mutableUrlRequest.setValue(cookie, forHTTPHeaderField: "Cookie")
Alamofire.request(mutableUrlRequest).responseJSON { (request, response, data, error) -> Void in
//handling the response
}
这篇关于带有 cookie 的 Alamofire 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!