我正在尝试从已删除的网站数据创建登录API(我已获得许可)。目前,网站的登录执行具有多个重定向的POST请求。在每次重定向时,似乎响应cookie总是包含一个新的SET-COOKIE,并伴有一些值,即会话ID。
我已经能够通过网站Hurtl.it以及Postman和Paw等程序获得完美的请求,但我无法通过Alamofire或NSURLSession获得正确填写的请求,除非我明确输入已返回的cookie来自Postman或Paw,其中包含重定向期间设置的其他cookie中的会话ID。
我想知道无论如何我都可以将Cookie设置为在Swift重定向期间自动更新并发送更新的Cookie。
这是当前正在使用的Alamofire代码,它返回正确的输出,但仅用于输入的会话ID / cookie,因此即使我更改了用户名/密码,它仍然会输出结果,就像它们从未需要更改一样: / p>
func sendRequestRequest() {
// Add Headers
let headers = [
"Cookie":"Cookie string taken explicitly from Paw or Postman",
"Content-Type":"application/x-www-form-urlencoded",
]
// Form URL-Encoded Body
let body = [
"inputEnterpriseId":"username",
"password":"password",
"queryString":"null",
"BTN_LOGIN":"Login",
]
// Fetch Request
Alamofire.request(.POST, "url", headers: headers, parameters: body, encoding: .URL)
.validate(statusCode: 200..<300)
.responseString { response in
if (response.result.error == nil) {
debugPrint("HTTP Response Body: \(response.result.value)")
}
else {
debugPrint("HTTP Request failed: \(response.result.error)")
}
}
}
如果有人需要更多信息,请告诉我。非常感谢你的帮助!
答案 0 :(得分:0)
我找到答案,但最终使用NSURLSession来做到这一点。修复我的cookie问题的部分是:
if let httpResponse = response as? NSHTTPURLResponse, let fields = httpResponse.allHeaderFields as? [String : String] {
let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(fields, forURL: response!.URL!)
NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookies(cookies, forURL: response!.URL!, mainDocumentURL: nil)
for cookie in cookies {
var cookieProperties = [String: AnyObject]()
cookieProperties[NSHTTPCookieName] = cookie.name
cookieProperties[NSHTTPCookieValue] = cookie.value
cookieProperties[NSHTTPCookieDomain] = cookie.domain
cookieProperties[NSHTTPCookiePath] = cookie.path
cookieProperties[NSHTTPCookieVersion] = NSNumber(integer: cookie.version)
cookieProperties[NSHTTPCookieExpires] = NSDate().dateByAddingTimeInterval(31536000)
let newCookie = NSHTTPCookie(properties: cookieProperties)
NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookie(newCookie!)
print("name: \(cookie.name) value: \(cookie.value)")
}