代码之家  ›  专栏  ›  技术社区  ›  zeeshan

如何使用Alamofire将CURL请求转换为Swift?

  •  2
  • zeeshan  · 技术社区  · 7 年前

    我使用的是Alamofire,我有一个如下的curl命令:

    curl "https://abc.mywebsite.com/obp/v3.1.0/my/page/accounts/myaccount1/account" -H 'Authorization: DirectLogin token="eyJhbGciOiJIUzI1NiIsInR5cCI6wkpeVeCJr.eyIiOiIifQ.MV-E150zMCrk6VrWv"' -H 'Content-Type: application/json'
    

    这个命令在命令行上运行良好,我成功地收到了响应。

    对于Swift,我在网上几乎没有找到对我不起作用的帮助,因此在这里发布了一个问题,我如何使用Swift打这个电话?

    理想情况下,我想使用Alamofire,因为这是我所有的网络电话使用。

    我有这样的东西,但它不工作,它给用户未经授权的错误,这意味着它是连接到服务器,但没有发送正确的参数。

    let url = "https://abc.mywebsite.com/obp/v3.1.0/my/page/accounts/myaccount1/account"
    let loginToken = "'Authorization' => 'DirectLogin token=\"eyJhbGciOiJIUzI1NiIsInR5cCI6wkpeVeCJr.eyIiOiIifQ.MV-E150zMCrk6VrWv\"', 'Content-Type' => 'application/json'"
    
    
    @IBAction func callAPIAction(_ sender: Any) {
        Alamofire
            .request(
                self.url,
                parameters: [
                    "token" : self.loginToken
                ]
            )
            .responseString {
                response in
                switch response.result {
                case .success(let value):
                    print("from .success \(value)")
                case .failure(let error):
                    print(error)
                }
        }
    }
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Markaos    7 年前

    看起来你想设置标题 Authorization 到 DirectLogin token="eyJhbGciOiJIUzI1NiIsInR5cCI6wkpeVeCJr.eyIiOiIifQ.MV-E150zMCrk6VrWv" . 你可以这样做:

    let loginToken = "DirectLogin token=\"eyJhbGciOiJIUzI1NiIsInR5cCI6wkpeVeCJr.eyIiOiIifQ.MV-E150zMCrk6VrWv\""
    
    ...
    
    @IBAction func callAPIAction(_ sender: Any) {
        Alamofire
            .request(
                self.url,
                headers: [
                    "Authorization": self.loginToken,
                    "Content-Type": "application/json"
                ]
            )
            .responseString {
                response in
                switch response.result {
                case .success(let value):
                    print("from .success \(value)")
                case .failure(let error):
                    print(error)
                }
        } 
    }
    
    ...