在swift中编码URLencoding

时间:2018-03-26 16:19:18

标签: ios iphone swift swift3

请帮我在Swift 3上做同样的事情

curl -X POST -d MD='44586989' -d TermUrl='https://proil.moscow/' --data-urlencode 'PaReq=+/eyJNZXJjaGFudE5hbWUiOm51bGwsIkZpcnN0U2l4IjoiNDI3NjM4IiwiTGFzdEZvdXIiOiIxMTQ1IiwiQW1vdW50IjoxMDM0LjAwLCJDdXJyZW5jeUNvZGUiOiJSVUIiLCJEYXRlIjoiMjAxOC0wMy0yNlQwMDowMDowMCswMzowMCIsIkN1c3RvbWVyTmFtZSI6bnVsbCwiQ3VsdHVyZU5hbWUiOiJydS1SVSJ9' https://demo.cloudpayments.ru/acs

我试试这个:

 var request = URLRequest(url: URL(string: acsUrlString)!)
    request.httpMethod = "POST"
    let session = URLSession.shared


    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    let d = String("PaReq=" + pareq + "&MD=" + String(Int(transactionId)) +  "&TermUrl=https://proil.moscow").data(using:String.Encoding.ascii, allowLossyConversion: false)
    request.httpBody = d

其中d没有编码= PaReq=+/eyJNZXJjaGFudE5hbWUiOm51bGwsIkZpcnN0U2l4IjoiNDI3NjM4IiwiTGFzdEZvdXIiOiIxMTQ1IiwiQW1vdW50IjoxMDM0LjAwLCJDdXJyZW5jeUNvZGUiOiJSVUIiLCJEYXRlIjoiMjAxOC0wMy0yNlQwMDowMDowMCswMzowMCIsIkN1c3RvbWVyTmFtZSI6bnVsbCwiQ3VsdHVyZU5hbWUiOiJydS1SVSJ9&MD=44586989&TermUrl=https://proil.moscow

所以这段代码给了我与

相同的结果
curl -X POST -d MD='44586989' -d TermUrl='https://proil.moscow/' -d PaReq='+/eyJNZXJjaGFudE5hbWUiOm51bGwsIkZpcnN0U2l4IjoiNDI3NjM4IiwiTGFzdEZvdXIiOiIxMTQ1IiwiQW1vdW50IjoxMDM0LjAwLCJDdXJyZW5jeUNvZGUiOiJSVUIiLCJEYXRlIjoiMjAxOC0wMy0yNlQwMDowMDowMCswMzowMCIsIkN1c3RvbWVyTmFtZSI6bnVsbCwiQ3VsdHVyZU5hbWUiOiJydS1SVSJ9' https://demo.cloudpayments.ru/acs

我从服务器cloudpayments收到此回复:" Check' +' PaReq参数中的符号。",

1 个答案:

答案 0 :(得分:0)

谢谢你,Rob,答案帮助了我。

request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.httpBody = postParameters.map { key, value in
   let keyString = key.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)!
   let valueString = (value as! String).addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)!
   return keyString + "=" + valueString
}.joined(separator: "&").data(using: .utf8)

和扩展名

extension CharacterSet {

static var urlQueryValueAllowed: CharacterSet = {
    let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
    let subDelimitersToEncode = "!$&'()*+,;="

    var allowed = CharacterSet.urlQueryAllowed
    allowed.remove(charactersIn: generalDelimitersToEncode + subDelimitersToEncode)

    return allowed
}()
}