简体   繁体   English

JSON和Alamofire请求问题

[英]Problems with JSON and Alamofire request

I am trying to send a request with the next code: 我正在尝试使用下一个代码发送请求:

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)
    }

}

But I am getting this 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 }

I am sending the request with paw http client and the response is ok. 我正在使用爪子http客户端发送请求,并且响应正常。

I am working with swift3, alamofire 4 and iOS10 我正在使用swift3,alamofire 4和iOS10

According to the response you have there it looks like your username and password is incorrect. 根据您的答复,您的用户名和密码似乎不正确。 Try printing the parameters dictionary to make sure it is correct. 尝试打印参数字典以确保其正确。 Something that can happen sometimes is if you forget to unwrap an optional value it will still get sent. 有时可能会发生的事情是,如果您忘记打开一个可选值,它将仍然被发送。 For example 例如

let optionalString:String? = "blablabla"

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

Edit: 编辑:

Another thing I noticed is you set the encoding to JSON but the header Content Type is PlainText. 我注意到的另一件事是将编码设置为JSON,但标头Content Type为PlainText。 Try setting the encoding to URLEncoding.default and make sure the headers are set appropriately for what the server is expecting. 尝试将编码设置为URLEncoding.default,并确保已针对服务器的期望正确设置了标头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM