Swift 2.0,Alamofire:在HTTP Post Request中设置cookie

时间:2015-10-12 14:06:42

标签: swift cookies swift2 nsurlrequest alamofire

我想在HTTP POST请求中设置Cookie。

下面的HTTP请求中的cookie字段,

version: 0.1.7
Cookie: client=Android; version=0.1.7; sellerId=SEL5483318784; key=178a0506-0639-4659-9495-67e5dffa42de
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Content-Length: 1431

我如何通过Alamofire实现这一目标?

我目前的Alamofire请求是这样的,

Alamofire.request(.POST, ServerConfig.ADD_PRODUCT_URL, parameters: productJSON, encoding: .JSON, headers: nil)
     .responseJSON(completionHandler: { responseRequest, responseResponse, responseResult in
         print(responseRequest!.URL)
         print(responseResponse)
         print(responseResult)
     })

5 个答案:

答案 0 :(得分:18)

我在项目上遇到了同样的问题,我做了类似的事情来解决它:

let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(response.allHeaderFields as! [String: String], forURL: response.URL!)
Alamofire.Manager.sharedInstance.session.configuration.HTTPCookieStorage?.setCookies(cookies, forURL: response.URL!, mainDocumentURL: nil)

你只需要这样做一次,因为Alamofire实例是一个单例,所以对于所有下一个请求都设置了cookie。

希望这就是你要找的东西:)

答案 1 :(得分:2)

斯威夫特3:

我的UserDefaults中保存了一系列Cookie,我将其附加到请求中的做法是:

var request = URLRequest(url: "https://yourURL.com")
if let cookies = cookies as? [HTTPCookie] {
   let headers = HTTPCookie.requestHeaderFields(with: cookies)
   request.allHTTPHeaderFields = headers
}

答案 2 :(得分:1)

感谢Jérémy,我能够:

Alamofire.request(.POST, url, ...)
    .responseJSON { 
    response in 
    HTTPClient.updateCookies(response)
    ...
}

static func updateCookies(response: Response<AnyObject, NSError>) {
    if let
        headerFields = response.response?.allHeaderFields as? [String: String],
        URL = response.request?.URL {
        let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(headerFields, forURL: URL)
        //print(cookies)
        // Set the cookies back in our shared instance. They'll be sent back with each subsequent request.
        Alamofire.Manager.sharedInstance.session.configuration.HTTPCookieStorage?.setCookies(cookies, forURL: URL, mainDocumentURL: nil)
    }
}

你很可能将它作为Request的扩展,因此.storeCookies()调用将成为.validate()。responseJSON()链接的一部分。

答案 3 :(得分:0)

iOS 11&amp; Alamofire 4

let webDataStore = webView.configuration.websiteDataStore
webDataStore.httpCookieStore.getAllCookies { (cookies) in
    Alamofire.SessionManager.default.session.configuration.httpCookieStorage?.setCookies(
        cookies,
        for: url,
        mainDocumentURL: nil
    )
}

答案 4 :(得分:0)

swift 5 and Xcode 11
let cookies = HTTPCookie.cookies(withResponseHeaderFields: response.response?.allHeaderFields as! [String: String], for: (response.response?.url)!)

Alamofire.SessionManager.default.session.configuration.httpCookieStorage?.setCookies(cookies, for: response.response?.url, mainDocumentURL: nil)