【问题标题】:alamofire 499 when making get request with headers and parametersalamofire 499 使用标头和参数发出获取请求时
【发布时间】:2016-12-26 00:06:30
【问题描述】:

我正在尝试使用带有 Swift 3 和 XCode 8 的 Alamofire 使用 JSON 参数和自定义标头发出 HTTP GET 请求。我已经能够通过一些不同的路由成功使用它,但我似乎无法特别是要破解其中的密码。下面是我试图做的等效 CURL 以及我试图用来复制它的 Swift 代码。

CURL 请求(有效):

curl -X GET url -d '{"xxxx": "111111111" }' -v -H "email: example@example.com" -H "token: ASDFJKL" -H 'Content-Type: application/json'

Alamofire 请求(不起作用):

    let headers: HTTPHeaders = [ "email": "example@example.com", "token": "ASDFJKL"]

    let parameters: Parameters = [ "xxxx": "111111111"]

    Alamofire.request(url, method: .get, parameters: parameters, encoding: JSONEncoding.default, 
headers: headers).responseJSON { response in
        debugPrint(response)
    }

如果有帮助,我会返回以下错误:

[Request]: <url>/<route>
[Response]: <NSHTTPURLResponse: 0x608000226fc0> { URL: <url> } { status code: 499, headers {
    "Cache-Control" = "no-cache, no-store";
    Connection = "keep-alive";
    "Content-Length" = 435;
    "Content-Type" = "text/html; charset=utf-8";
    Date = "Sun, 25 Dec 2016 23:45:38 GMT";
    Server = Cowboy;
} }
[Data]: 435 bytes
[Result]: FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))
[Timeline]: Timeline: { "Request Start Time": 504402284.293, "Initial Response Time": 504402339.616, "Request Completed Time": 504402339.617, "Serialization Completed Time": 504402339.617, "Latency": 55.323 secs, "Request Duration": 55.324 secs, "Serialization Duration": 0.000 secs, "Total Duration": 55.324 secs }

【问题讨论】:

    标签: ios swift http alamofire


    【解决方案1】:

    一个问题是您尝试在请求正文中发送 JSON,但您是在 GET 请求中执行此操作。但是请求的主体在 GET 请求中是未定义的,因为数据应该在 URL 中。如果您在请求中包含正文,您确实应该使用POST,而不是GET

    显然curl 正在设置GET 请求的主体,因为您提供了设置-X GET(即使-d 选项说它使用POST 请求;并且如果您省略了@987654330 @,由于-d 选项,默认情况下它确实会使其成为POST 请求)。

    但是URLSession 不允许您为GET 请求指定httpBody(也不应该)。如果你想在请求体中发送数据,你应该使用POST(即在Alamofire中requestmethod应该是.post)。

    【讨论】:

    • 这非常有帮助。非常感谢。 curl 工作的事实让我失望,所以有助于理解为什么会这样。我将在 POSTS 的请求正文中为 GET 和 JSON 使用 URL 编码的参数。
    猜你喜欢
    • 2018-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-07
    • 1970-01-01
    相关资源
    最近更新 更多