我正在尝试使用带有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 }
答案 0 :(得分:3)
一个问题是您尝试在请求正文中发送JSON,但是您在GET
请求中执行此操作。但是请求的主体在POST
请求中未定义,因为数据应该在URL中。如果您在请求中包含正文,那么您真的应该GET
,而不是curl
。
显然GET
正在设置-X GET
请求的正文,因为您已经提供了设置-d
(即使POST
选项表示它使用{ {1}}请求;如果您省略了-X GET
,由于POST
选项,默认情况下它确实会成为-d
请求。
但URLSession
不允许您为httpBody
请求指定GET
(也不应该)。如果您想在请求正文中发送数据,则应POST
(即在Alamofire request
中,method
应为.post
)。