如何在Swift中使用URLSession创建特定的curl请求

omvjsjqw  于 2023-04-04  发布在  Swift
关注(0)|答案(1)|浏览(102)

外观:curl https://token-vault.repeatphotos.xyz/token -H "Authorization: e11f18b4-5015-45ad-8276-18269a7bf047""响应是字符串值。所以主要的问题是,如何在Swift中发出请求并从中获取值?我已经尝试了类似这样的方法:

func changeApiKey() {
        let url = URL(string: "https://token-vault.repeatphotos.xyz/token")

        var request = URLRequest(url: url!)

        request.httpMethod = "GET"
        request.addValue("e11f18b4-5015-45ad-8276-18269a7bf047", forHTTPHeaderField: "Authorization")

        let task = URLSession.shared.dataTask(with: url!) { data, response, error in
            guard error == nil else {
                print(error!)
                return
            }
            guard let data = data else {
                print("Data is empty")
                return
            }

            let json = try! JSONSerialization.jsonObject(with: data, options: [])
            print(json)
        }
        task.resume()
    }
a0x5cqrl

a0x5cqrl1#

尝试这样的东西,为我工作,它给“newty-token”

func changeApiKey() {
    if let url = URL(string: "https://token-vault.repeatphotos.xyz/token") {
        
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        request.setValue("text/plain",forHTTPHeaderField: "Accept")
        request.setValue("e11f18b4-5015-45ad-8276-18269a7bf047", forHTTPHeaderField: "Authorization")
        
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard error == nil else {
                print(error!)
                return
            }
            guard let data = data else {
                print("Data is empty")
                return
            }
            
            let result = String(data: data, encoding: .utf8)
            print("result: \(result)")
            
        }
        task.resume()
    }
}

相关问题