我需要像邮递员一样提出要求,但在Alamofire中
curl -X DELETE \ http://someUrl \ -H 'authorization: JWT someToken' \ -H 'cache-control: no-cache' \ -H 'content-type: application/x-www-form-urlencoded' \ -H 'postman-token: 0149ef1e-5d45-34ce-3344-4b658f01bd64' \ -d id=someId
我想应该是这样的:
let headers = ["Content-Type": "application/x-www-form-urlencoded", "Authorization": "JWT someToken"] let params: [String: Any] = ["id": "someId"] Alamofire.request("http://someUrl", method: .delete, parameters: params, headers: headers).validate().responseJSON { responseJSON in switch responseJSON.result { case .success( _): let data = responseJSON.result.value! print(data) case .failure(let error): print(error.localizedDescription) } }
我该如何检查我的请求是否具有以下选项cUrl--d id=someId
cUrl
-d id=someId
你做这个:
Alamofire.request("http://someUrl", method: .delete, parameters: params, headers: headers).validate().responseJSON { ... }
实际上,它可以像这样被解构:
let request = Alamofire.request("http://someUrl", method: .delete, parameters: params, headers: headers) request.validate().responseJSON { ... }
request是一个DataRequest,它继承自Request其中,具有debugDescription对该调用的相当大的覆盖curlRepresentation()。
request
DataRequest
Request
debugDescription
curlRepresentation()
如果打印request,则将具有:
$> CredStore - performQuery - Error copying matching creds. Error=-25300, query={ atyp = http; class = inet; "m_Limit" = "m_LimitAll"; ptcl = http; "r_Attributes" = 1; sdmn = someUrl; srvr = someUrl; sync = syna; } $ curl -v \ -X DELETE \ -H "Accept-Encoding: gzip;q=1.0, compress;q=0.5" \ -H "User-Agent: iOSTest/1.0 (nt.iOSTest; build:1; iOS 11.4.0) Alamofire/4.7.3" \ -H "Accept-Language: en;q=1.0, fr-FR;q=0.9" \ "http://someUrl?id=someId"
很酷吧?但是别无选择-d。您甚至可以使用进行检查print(request.request.httpBody)并获得:
-d
print(request.request.httpBody)
$> nil
要修复它,请在init中使用encoding(ParameterEncoding)参数。您可以通过默认情况下使用JSONEncoding,URLEncoding和PropertyListEncoding。
encoding
ParameterEncoding
JSONEncoding
URLEncoding
PropertyListEncoding
但您要将参数放在中httpBody,因此请使用URLEncoding(destination: .httpBody):
httpBody
URLEncoding(destination: .httpBody)
Alamofire.request("http://someUrl", method: .delete, parameters: params, encoding: URLEncoding(destination: .httpBody), headers: headers)
然后您将获得:
$>CredStore - performQuery - Error copying matching creds. Error=-25300, query={ atyp = http; class = inet; "m_Limit" = "m_LimitAll"; ptcl = http; "r_Attributes" = 1; sdmn = someUrl; srvr = someUrl; sync = syna; } $ curl -v \ -X DELETE \ -H "Authorization: JWT someToken" \ -H "User-Agent: iOSTest/1.0 (nt.iOSTest; build:1; iOS 11.4.0) Alamofire/4.7.3" \ -H "Accept-Language: en;q=1.0, fr-FR;q=0.9" \ -H "Content-Type: application/x-www-form-urlencoded" \ -H "Accept-Encoding: gzip;q=1.0, compress;q=0.5" \ -d "id=someId" \ "http://someUrl"