iOS |服务器返回415状态代码(Swift 3)

时间:2017-06-08 12:31:45

标签: json swift

我正在向使用ASP.NET Core构建的服务器发送登录信息。我通过PostMan和Fiddler测试了我的服务器,它返回了一个有效的响应。

这是我的帖子请求:

   var request = URLRequest(url: URL(string:     "http://adincebic.com/auth/login")!)
    request.httpMethod = "POST"
    let postString = "email=cebic.ad@gmail.com&password=a"
    request.httpBody = postString.data(using: .utf8)
    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=\(String(describing: 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 = \(String(describing: response))")
        }

        let responseString = String(data: data, encoding: .utf8)
        print("responseString = \(String(describing: responseString))")
    }
    task.resume()

我尝试使用字典,如["电子邮件":" myEmail","密码":" myPass"]但它没有让我这样做。 我也尝试过使用Alamofire但是没有运气,服务器总是在控制台中返回415错误。

要验证我的服务器是否正常工作,我创建了一个UWP应用程序来测试它并且它按预期工作。

这是我在XCode中的服务器响应:

   statusCode should be 200, but is 415
   response = Optional(<NSHTTPURLResponse: 0x6080002275a0> { URL:        http://adincebic.com/auth/login } { status code: 415, headers {
Connection = "keep-alive";
"Content-Length" = 0;
Date = "Thu, 08 Jun 2017 12:16:12 GMT";
Server = "nginx/1.10.1 (Ubuntu)";
} })
responseString = Optional("")

我假设它可能是编码问题或读取数据的问题。

我写了这篇帖子请求,如本答案所述:HTTP Request in Swift with POST method

1 个答案:

答案 0 :(得分:1)

也许你错过了Content-Type标题,如下所示:

request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")