在Swift中将curl转换为URL请求

在Swift中将curl转换为URL请求

本文介绍了在Swift中将curl转换为URL请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

curl请求示例如下,我无法迅速将其转换为url请求.

The curl request example is as follows, I am having trouble converting it to a url request in swift.

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'

这是我认为的样子,但是它没有按我期望的那样工作.

This is how I think it should look like but it isnt working as I am expecting.

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

推荐答案

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

You're adding the binary data as a header, instead you should convert the string to data and add it to the httpBody property of the request.

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

这篇关于在Swift中将curl转换为URL请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 06:27