JSON和Alamofire请求的问题

时间:2017-01-16 20:52:06

标签: ios swift swift3 alamofire

我正在尝试使用下一个代码发送请求:

func getLogin(user: String, password: String) {
    let url = URL(string: "https://www.url.es/api/login")!

    let parameters: Parameters = [
        "usuario" : "\(user)",
        "clave" : "\(password)"]

    let headers: HTTPHeaders = [
        "Authorization": "Basic TOKEN"
    ]

    Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).validate()
        .responseJSON { response in
            print("repuesta")
            print(response.request as Any)  // original URL request
            print(response.response as Any) // URL response
            print(response.result.value as Any)   // result of response serialization

            debugPrint(response)
    }

}

但我收到了这个回复:

[Request]: https://www.url.es/api/login
[Response]: <NSHTTPURLResponse: 0x608000220b40> { URL: https://www.url.es/api/login } { status code: 401, headers {
    "Cache-Control" = "no-cache";
    "Content-Length" = 28;
    "Content-Type" = "text/plain; charset=utf-8";
    Date = "Mon, 16 Jan 2017 20:44:14 GMT";
    Expires = "-1";
    Pragma = "no-cache";
    Server = "Microsoft-IIS/8.5";
    "Www-Authenticate" = Bearer;
    "X-AspNet-Version" = "4.0.30319";
    "X-Powered-By" = "ASP.NET";
} }
[Data]: 28 bytes
[Result]: FAILURE: responseValidationFailed(Alamofire.AFError.ResponseValidationFailureReason.unacceptableStatusCode(401))
[Timeline]: Timeline: { "Request Start Time": 506292395.911, "Initial Response Time": 506292396.351, "Request Completed Time": 506292396.352, "Serialization Completed Time": 506292396.353, "Latency": 0.440 secs, "Request Duration": 0.441 secs, "Serialization Duration": 0.000 secs, "Total Duration": 0.441 secs }

我用paw http客户端发送请求,响应没问题。

我正在使用swift3,alamofire 4和iOS10

1 个答案:

答案 0 :(得分:0)

根据您的回复,您的用户名和密码看起来不正确。尝试打印参数字典以确保它是正确的。有时会发生的事情是,如果您忘记打开可选值,它仍会被发送。例如

let optionalString:String? = "blablabla"

print(optionalString) //prints: Optional(blablabla)

编辑:

我注意到的另一件事是您将编码设置为JSON,但标题内容类型是PlainText。尝试将编码设置为URLEncoding.default,并确保为服务器期望的内容设置适当的标头。