Converting curl to URL request in Swift

丶灬走出姿态 提交于 2021-01-29 07:49:42

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!