问题
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")
回答1:
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)
来源:https://stackoverflow.com/questions/57760182/converting-curl-to-url-request-in-swift