使用Alamofire将cURL转换为HTTP请求(Swift 3)



我无法在贝宝中获得访问令牌,在此之前,这是确切的方法吗?我有点困惑。这是我真正需要转换的:

curl-vhttps://api.sandbox.paypal.com/v1/oauth2/token\
-H"接受:application/json"\
-H"接受语言:en_US"\
-u"EOJ2S-Z6OoN_le_KS1d75wsZ6y0SFdVsY9183VixFyZp:EClusMEUk8e9ihI7ZdVLF5cZ6yOSFdVsy9183Vix FyZp"\
-d"grant_type=client_credentials">

这是我用来转换它的片段

let parameters = ["password" : K_CLIENT_SECRET, "username" : K_CLIENTID_SANDBOX, "grant_type" : "client_credentials"]
let str = "(K_CLIENTID_SANDBOX):(K_CLIENT_SECRET)"
let utf8str = str.data(using: String.Encoding.utf8)
//let basic_auth_token = utf8str?.base64EncodedStringWithOptions(NSData.Base64EncodingOptions(rawValue: 0))
let basic_auth_token = utf8str?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
let headers = ["Accept" : "application/json", "Authorization" :"Basic "+basic_auth_token!] 
Alamofire.request("https://api.sandbox.paypal.com/v1/oauth2/token", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers )
.responseJSON { response in
print(response.request as Any)  // original URL request
print(response.response as Any) // URL response
print(response.result.value as Any)   // result of response serialization
}

此处为响应:打印时我得到了三件事:(但响应值为零)

可选(https://api.sandbox.paypal.com/v1/oauth2/token)

可选({URL:https://api.sandbox.paypal.com/v1/oauth2/token}{状态码:415,收割台{连接=关闭;"内容长度"=0;"内容类型"="text/plain;charset=ISO-8859-1";日期="2017年1月25日星期三06:00:37 GMT";"Paypal调试Id"="6221061b57a,6221061b57a0a";服务器=Apache;"Set-Cookie"="X-PP-SILOVER=名称%3DSANDBOX3.API.1%26silo_version%3D1880%26app%3D平台服务器%26TIME%3D849752%26HTTP_X_PP_AZ_LOCATOR%3Ddcg12.slc;到期时间=2017年1月25日星期三06:30:37 GMT;domain=.paypal.com;路径=/;保护HttpOnly,X-PP-SILOVER=;过期时间=1970年1月1日星期四00:00:01GMT";Vary=授权;}})

我得到了解决方案,它是:

//GET ACCESS TOKEN
let parameters = ["password" : K_CLIENT_SECRET, "username" : K_CLIENTID_SANDBOX, "grant_type":"client_credentials"]    
let str = "(K_CLIENTID_SANDBOX):(K_CLIENT_SECRET)"
let utf8str = str.data(using: String.Encoding.utf8)
//let basic_auth_token = utf8str?.base64EncodedStringWithOptions(NSData.Base64EncodingOptions(rawValue:
0))
let basic_auth_token = utf8str?.base64EncodedString(options:
NSData.Base64EncodingOptions(rawValue: 0))
let headers = ["Accept" : "application/json", "Authorization" :"Basic "+basic_auth_token!]
Alamofire.request("https://api.sandbox.paypal.com/v1/oauth2/token",
method: .post, parameters: parameters, encoding:URLEncoding.default,
headers: headers)
.responseJSON { response in
SwiftLoader.hide()
print(response.request as Any)  // original URL request
print(response.response as Any) // URL response
print(response.result.value as Any)   // result of response serialization

}

最新更新