Search code examples
iosswifthttpalamofire

alamofire 499 when making get request with headers and parameters


I'm trying to make a HTTP GET request with JSON parameters and custom headers using Alamofire with Swift 3 and XCode 8. I've been able to use it successfully with a few different routes already, but I can't seem to crack the code on one in particular. Below is the equivalent CURL I'm trying to do and the Swift code I'm trying to use to replicate it.

CURL request (works):

curl -X GET url -d '{"xxxx": "111111111" }' -v -H "email: [email protected]" -H "token: ASDFJKL" -H 'Content-Type: application/json'

Alamofire request (doesn't work):

    let headers: HTTPHeaders = [ "email": "[email protected]", "token": "ASDFJKL"]

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

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

Here is the error I'm getting back if it helps:

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

Solution

  • One issue is that you're trying to send JSON in the body of the request, but you're doing it in a GET request. But the body of the request is undefined in GET requests, as the data should be in the URL. If you are including a body to a request, you really should do a POST, not a GET.

    Apparently curl is setting the body of a GET request because you've supplied set the -X GET (even though the -d option says that it uses POST requests; and if you omitted -X GET, it would indeed make it a POST request by default because of the -d option).

    But URLSession doesn't allow you to specify a httpBody for a GET request (nor should it). If you want to send data in the body of a request, you should do POST (i.e. in the Alamofire request, the method should be .post).