我使用带有
URLRequest
和 URLSession
的 POST 请求通过 API 登录。自从我收到来自 API 的正确响应以来,一切似乎都运行良好。
然后我想向同一个 API 发送 GET 请求,但似乎我不再连接了。
据我所知,API 在其标头中以这种形式发送 Cookie:
Cookie:PHPSESSID=abc123
我猜问题出在我执行 GET 请求时未发送的 cookie。
这是我的代码。
视图控制器:
@IBAction func Connection(_ sender: AnyObject) {
let loginFunc = Login()
loginFunc.login(username: username.text!, password: password.text!) { jsonString in
let response = jsonString
print(response)
}
let get = GetRequest()
get.get(req: "patient/info") { jsonString in
let response = jsonString
print(response)
}
}
登录.swift:
class Login {
func login(username: String, password: String, completion: @escaping (String) -> ()) {
var request = URLRequest(url: URL(string: "http://myurl/web/app_dev.php/login_check")!)
request.httpMethod = "POST"
let config = URLSessionConfiguration.default
let postString = "_username=" + username + "&_password=" + password
request.httpBody = postString.data(using: .utf8)
var responseString = ""
let mysession = URLSession.init(configuration: config)
let task = mysession.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
responseString = String(data: data, encoding: .utf8)!
let httpResponse = response as! HTTPURLResponse
let field = httpResponse.allHeaderFields["Cookie"]
print(field)
print(type(of: response))
completion(responseString)
}
task.resume()
}
}
GetRequest.swift:
class GetRequest {
func get(req: String, completion: @escaping (String) -> ()) {
var request = URLRequest(url: URL(string: "http://myurl/web/app_dev.php/" + req)!)
request.httpMethod = "GET"
var responseString = ""
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
responseString = String(data: data, encoding: .utf8)!
print(responseString)
completion(responseString)
}
task.resume()
}
}
嘿,请使用随 ajax 请求一起发送 cookie。您需要将 withCredentials 设置为 true。
$.ajaxSetup({
dataType: 'json',
contentType: 'application/json',
async: true,
cache: false,
processData: false,
crossDomain: true,
xhrFields: {
withCredentials: true
}
});