swift2 雨燕2.0,阿拉莫菲尔:在HTTP Post请求中设置Cookie

qf9go6mv  于 2022-11-06  发布在  Swift
关注(0)|答案(5)|浏览(176)

我想在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.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)
     })
nbewdwxp

nbewdwxp1#

我在一个项目中遇到了同样的问题,我做了如下的事情来解决它:

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。
希望这就是你要找的:)

aemubtdh

aemubtdh2#

雨燕三:
我在UserDefaults中保存了一组cookie,我将它们附加到请求中的操作是:

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

ecr0jaav3#

多亏了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()链接的一部分。

voase2hg

voase2hg4#

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)
tct7dpnv

tct7dpnv5#

iOS 11和阿拉莫之火4

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

相关问题