Reputation: 3605
I've a django REST api which works perfectly when called over POSTMAN or an android client. However when I try to call it in Swift I get a 405.
This is my code,
import Foundation
let url = URL(string: "http://example.com/xx/x/xxx/sports")!
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let postString = "client_id=xx&client_secret=yy"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else {return}
do{
//try validate(response)
//parse data
print(response)
}catch{
print(error)
}
//print(String(describing: data))
}
task.resume()
Can someone help me with this?
Upvotes: 2
Views: 1184
Reputation: 3082
405 Method Not Allowed response status code indicates that the request method is known by the server but is not supported by the target resource.
The server MUST generate an Allow header field in a 405 response containing a list of the target resource's currently supported methods.
Check the httpMethod. You may need GET
or other HTTP method instead of POST
Replace
let postString = "client_id=xx&client_secret=yy"
with
let postString = "{client_id=\"xx\", client_secret=\"yy\"}"
Also you should use URLSession.shared.dataTask(with: request)
not with url
. See the code below:
URLSession.shared.dataTask(with: request) { data, response, error in
if let response = response, let data = data {
print(response)
print(String(data: data, encoding: .utf8))
} else {
print(error)
}
}
As you're using
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in...
Your request
setup code is ignored. GET method is default, and it is not allowed on
your server.
Upvotes: 2
Reputation: 2446
I've a django REST api which works perfectly when called over POSTMAN or an android client.
If it is working on POSTMAN Then you can get that code from that itself. Copy that code and paste in Playground. It should work. Compare with your code. Fix the issues.
Upvotes: 0