【发布时间】:2019-08-03 20:57:02
【问题描述】:
我想向 apache Web 服务器发出“GET”请求以检索一些数据。在发出上述请求之前,我登录发出“POST”请求,Web 服务器打开一个新会话,我得到 json 响应:
gotten json response dictionary is
["user": {
email = "asd@asd.it";
password = "<null>";\\ for security reason it doesn't return the password
sessionID = 6C61269BB7BB40682E96AD80FF8F1CB7;
}]
到目前为止,一切都是正确的。但是当我尝试发出“GET”请求来检索用户的数据时,我得到了这个响应:
gotten json response dictionary is
["message": {
errorCode = F01;
errorDetails = "No session is found in the server, either you have not set the JSESSIONID cookie or the session does not exists";
message = "No session Found";
}]
“POST”请求的代码是:
let urlComp = NSURLComponents(string: "http://localhost:8080/mnemosyne/auth")!
let postDict: [String:Any] = ["email": "asd@asd.it", "password" : "password"]
var items = [URLQueryItem]()
for (key,value) in postDict {
items.append(URLQueryItem(name: key, value: value as? String))
}
urlComp.queryItems = items
var urlRequestAuth = URLRequest(url: urlComp.url!, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 10.0 * 1000)
urlRequestAuth.httpMethod = "POST"
let postData = try? JSONSerialization.data(withJSONObject: postDict, options: [])
urlRequestAuth.httpBody = postData
let taskAuth = URLSession.shared.dataTask(with: urlRequestAuth) { (data, response, error) in
guard error == nil else {
print(error as Any)
return
}
guard let content = data else {
print("No data")
return
}
guard let json = (try? JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers)) as? [String: Any] else {
print("Not containing JSON")
return
}
print("gotten json response dictionary is \n \(json)")
}
taskAuth.resume()
这是“GET”的代码:
let url = URL(string: "http://localhost:8080/mnemosyne/rest/task")
var request = URLRequest(url: url!)
let taskTask = URLSession.shared.dataTask(with: request) { (data, response, error) in
guard error == nil else {
print ("error: \(error!)")
return
}
guard let content = data else {
print("No data")
return
}
guard let json = (try? JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers)) as? [String: Any] else {
print("Not containing JSON")
return
}
print("gotten json response dictionary is \n \(json)")
}
taskTask.resume()
有什么问题?如何在请求中传递我要使用的会话 ID?
【问题讨论】:
-
我相信您必须在下一个 api 请求
sessionID = 6C61269BB7BB40682E96AD80FF8F1CB7中传递此值,以便您的服务器可以验证登录和会话以继续请求。
标签: ios json swift webserver httprequest