【问题标题】:Converting curl to URL request in Swift在 Swift 中将 curl 转换为 URL 请求
【发布时间】:2019-09-03 00:31:15
【问题描述】:

curl请求示例如下,我在swift中无法将其转换为url请求。

curl --include --request POST \
--header "application/x-www-form-urlencoded" \
--data-binary "grant_type=client_credentials&client_id=PUBLIC_KEY&client_secret=PRIVATE_KEY" \
'https://api.tcgplayer.com/token'

这是我认为它应该看起来的样子,但它没有按我的预期工作。

 guard let url = URL(string: "https://api.tcgplayer.com/token") else { return }
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")  
    request.addValue("grant_type=client_credentials&client_id=\(TCGPlayerClient.publicKey)&client_secret=\(TCGPlayerClient.privateKey)", forHTTPHeaderField: "data-binary")

【问题讨论】:

  • 你需要设置httpBody数据,而不是作为新的header发送。

标签: ios swift curl


【解决方案1】:

您将二进制数据作为标头添加,而应将字符串转换为数据并将其添加到请求的httpBody 属性中。

request.httpBody = "YOUR STRING HERE".data(using: .utf8)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-10
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    • 2017-08-03
    • 2018-04-16
    • 2021-02-06
    相关资源
    最近更新 更多