Json响应“ GET”请求:“未找到会话”-Swift

时间:2019-08-03 20:57:02

标签: ios json swift webserver httprequest

我想向apache网络服务器发出“ 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?

1 个答案:

答案 0 :(得分:0)

我认为您需要在GET请求中发送sessionID。

我首先会尝试使用诸如Postman或RESTed免费应用程序之类的工具来测试请求并了解如何发送正确的POST请求。

取决于服务器的实现-您可以在POST正文或POST标头中将会话ID作为url的一部分发送。