英文:
How to make specific curl request in swift using URLSession
问题
如何看起来: `curl https://token-vault.repeatphotos.xyz/token -H "Authorization: e11f18b4-5015-45ad-8276-18269a7bf047""` 响应是字符串值。因此,主要问题是如何在Swift中发出请求并获取该值?
我尝试过类似这样的代码:
```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()
}
<details>
<summary>英文:</summary>
How it looks: `curl https://token-vault.repeatphotos.xyz/token -H "Authorization: e11f18b4-5015-45ad-8276-18269a7bf047""` Response is string value. So the main question is, how to make a request and get value from this in swift?
I've tried something like this:
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()
}
</details>
# 答案1
**得分**: 0
尝试像这样做,对我有效,它提供了 "newty-token":
```swift
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()
}
}
英文:
try something like this, works for me, it gives "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()
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论