带-d的Alamofire

时间:2018-12-05 17:11:10

标签: swift curl alamofire

我需要像邮递员一样发出请求,但在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

这样的选项?

1 个答案:

答案 0 :(得分:3)

您这样做:

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 { ... }

requestDataRequest,它继承自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)进行检查并获得:

$> nil

要修复此问题,请在init中使用encodingParameterEncoding)参数。您可以默认使用JSONEncodingURLEncodingPropertyListEncoding

但是您想将参数放在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"