Swfit 4 JSON添加自定义标题

时间:2018-03-26 10:59:13

标签: json swift request swift4

如何在服务器上发送GET请求时添加自定义标头。 我试过了

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我是初学者所以如果有任何错误,请指出并帮助我改进。提前谢谢。

2 个答案:

答案 0 :(得分:1)

如果您的目的是使用令牌对API进行身份验证,则会为Authorization标头设置错误的格式。令牌授权也称为“承载授权”,格式如下:

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()

您不需要Content-Type标头,因为GET请求没有正文内容。

答案 1 :(得分:0)

尝试以下代码:

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())