Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send post request with bearer token and json body in Swift

I'm pretty new to swift and i tried to make a post request to a website, but couldn't come up with an working result, yet. All examples I found didn't work for me either.

I need to send a json body to https://mypostrequestdestination.com/api/

The json body only contains of one value

{State:1}

And the Header has to contain

{"Authorization": bearer "token"}

{"Accept":"application/json"}

{"Content-Type":"application/json"}

Hope someone can help me.

Thanks!

like image 841
Mason Avatar asked Sep 15 '18 18:09

Mason


People also ask

How do I send a POST request with Bearer Token?

To send a POST JSON request with a Bearer Token authorization header, you need to make an HTTP POST request, provide your Bearer Token with an Authorization: Bearer {token} HTTP header and give the JSON data in the body of the POST message.

How do you pass a Bearer Token in header?

To send a GET request with a Bearer Token authorization header, you need to make an HTTP GET request and provide your Bearer Token with the Authorization: Bearer {token} HTTP header.

How do I send a header token?

To send a request with the Bearer Token authorization header, you need to make an HTTP request and provide your Bearer Token with the "Authorization: Bearer {token}" header. A Bearer Token is a cryptic string typically generated by the server in response to a login request.


1 Answers

This one worked for me

let token = "here is the token"
let url = URL(string: "https://mypostrequestdestination.com/api/")!

// prepare json data
let json: [String: Any] = ["State": 1]

let jsonData = try? JSONSerialization.data(withJSONObject: json)

// create post request
var request = URLRequest(url: url)
request.httpMethod = "POST"

// insert json data to the request
request.httpBody = jsonData
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.setValue( "Bearer \(token)", forHTTPHeaderField: "Authorization")

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
        print(error?.localizedDescription ?? "No data")
        return
    }
    let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
    if let responseJSON = responseJSON as? [String: Any] {
        print(responseJSON)
    }
}

task.resume()
like image 183
Mason Avatar answered Oct 22 '22 06:10

Mason