sawin0
sawin0

Reputation: 663

Swfit 4 JSON adding custom header

How can I add custom header while sending GET request on server. I have tried

var request = URLRequest(url: URL(string: URL)!)
    request.httpMethod = "GET"
    //        request.addValue("2", forHTTPHeaderField: "x-api-version")
    request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

P.S I am beginner so if there is any mistake please point it out and help me to improve. Thank you in advance.

Upvotes: 1

Views: 1869

Answers (2)

Code Different
Code Different

Reputation: 93181

If your purpose is to authenticate to the API using a token, you set the wrong format for the Authorization header. Token authorization is also called "bearer authorization", the format is below:

let url = URL(string: "https://httpbin.org/get")!
let token = "abcdef"

var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")

URLSession.shared.dataTask(with: request) { data, response, error in
    guard error == nil else { print(error!); return }
    guard let data = data else { print("No data"); return }

    if let str = String(data: data, encoding: .utf8) {
        print(str)
    }
}.resume()

You don't need the Content-Type header since a GET request has no body content.

Upvotes: 1

vaibhav
vaibhav

Reputation: 4096

Try below code:

func setHeader() -> [String : String] {
    let dictionary = [
        "Accept":"application/json",
        "Content-Type":"application/json",
        "Authorization": "your_authtoken"
        // more headers here
    ]
    return dictionary
}

// calling
request(endPoint, method: .post, parameters: params, encoding:JSONEncoding.default, headers: setHeader())

Upvotes: 0

Related Questions