0

I have an API call with oauth which I tested with correct authorization token in postman.I am getting proper response in postman. But when I try same thing in Swift, I get 504 error.

I have checked every params and headers properly and everything looks same as postman. Not sure why samething is working in postman and gives 504 error in swift. what could be issue?

var params = [String : String]()
params["Id"] = Id;

var headers = [String : String]()
headers["api-key"] = "XXXXXX"
headers["Authorization"] = "Bearer XXX" 

do{
    var request = URLRequest(url: URL(string: getURL())!)
    request.allHTTPHeaderFields = headers
    request.httpBody = try JSONSerialization.data(withJSONObject: params , options: [])
    request.httpMethod = "GET"
    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
        let httpResponse = response as! HTTPURLResponse
        print(httpResponse)
    }
    task.resume()
}catch{
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579

1 Answers1

0

When using a GET request, there is no body to the request. Everything goes on the URL.

Also are you sure that in Postman you are using only those 2 headers?

See if something like this works for you:

var params: Parameters = Parameters()
params.updateValue(Id, forKey: "Id")

var components = URLComponents(string: getURL())!
components.queryItems = params.map { (key, value) in
    URLQueryItem(name: key, value: value)
}
components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
let request = URLRequest(url: components.url!)
request.setValue("XXXXXX", forHTTPHeaderField: "api-key")
request.setValue("Bearer XXX", forHTTPHeaderField: "Authorization")
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {                                                 // check for fundamental networking error
        print("error=\(error)")
        return
    }

    if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
        print("statusCode should be 200, but is \(httpStatus.statusCode)")
        print("response = \(response)")
    }

    let responseString = String(data: data, encoding: .utf8)
    print("responseString = \(responseString)")
}
task.resume()