Swift HTTP Post Request返回网站的HTML而不是JSON响应

时间:2018-03-27 13:08:09

标签: ios swift http post urlsession

我正在尝试访问应该使用用户名和密码的网站,并返回一个JSON,其中包含说明所提供的登录数据是否有效的信息。 但是,我回来的只是网站的HTML代码而不是回复。我已经在https://www.hurl.it/上使用相同的参数尝试了请求,并且得到了正确的响应,因此这似乎不是问题。

我使用以下代码:

private func uploadToAPI(username: String, password: String) {

guard let url = URL(string: "http://api.foo.com/login.php"),
  let encodedUsername = username.addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics),
  let encodedPassword = password.addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics) else {

  self.loginButton.isLoading = false
  return
}

let httpBodyParameters = ["user": encodedUsername, "password": encodedPassword, "client": "ios", "version": "5"]

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: httpBodyParameters, options: JSONSerialization.WritingOptions.prettyPrinted)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")

URLSession.shared.dataTask(with: request) { (data, response, error) in

  if let response = response {
    print(response.mimeType) // Prints "text/html"
  }

  if let data = data {
    print(try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments)) // Prints nil
    print(String(data: data, encoding: String.Encoding.utf8)) // Prints the site's HTML
  }

}.resume()

 }

我没看到问题出在哪里。我也尝试过不设置HTTP标头,但没有区别。有人有任何想法吗?

1 个答案:

答案 0 :(得分:0)

似乎没有设置HTTP头字段并使用字符串文字而不是字典,因为HTTP正文数据为我做了。

对于任何感兴趣的人,这是现在收到预期响应的代码:

  guard let url = URL(string: "http://api.foo.com/login.php?"),
      let encodedUsername = username.addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics),
      let encodedPassword = password.addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics) else {
        if let delegate = self.delegate {
          delegate.viewModelDidRejectLogin(self)
        }
        return
    }

    let httpBodyString = "user=\(encodedUsername)&password=\(encodedPassword)&client=ios&version=5"

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.httpBody = httpBodyString.data(using: String.Encoding.utf8)

    URLSession.shared.dataTask(with: request) { (data, response, error) in

      guard let data = data, error == nil else {
        print(error)
        return
      }

      do {
        if let json = try JSONSerialization.jsonObject(with: data) as? [String : AnyObject] {
          self.readLoginResponse(json)
        }
      } catch {
        print(error)
      }

    }.resume()