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

问题描述:

我正在使用 Alamofire 并且我有一个像这样的 curl 命令:

I am using Alamofire and I have a curl command like this:

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'

此命令在命令行上运行良好,我成功收到了响应.

This command works fine on command line and I receive a response successfully.

对于 Swift,我在网上找到的帮助很少,这对我不起作用,因此在此处发布一个问题,我如何使用 Swift 进行此调用?

For Swift I have found very little help online which didn't work for me, and so posting a question here, how can I make this call using Swift?

理想情况下,我想使用 Alamofire,因为我所有的网络调用都使用它.

Ideally I would like to use Alamofire since that's what I use for all my network calls.

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

I have something like this but it doesn't work, it give User Unauthorized error, which means that it is connecting to the server but not sending the parameters correctly.

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)
            }
    }
}

看起来您想将标题 Authorization 设置为 DirectLogin token="eyJhbGciOiJIUzI1NiIsInR5cCI6wkpeVeCJr.eyIiOiIifQ.MV-E150zMCrk6VrWvrW"DirectLogin token="eyJhbGciOiJIUzI1NiIsInR5cCI6wkpeVeCJr./代码>.你可以这样做:

It looks like you want to set header Authorization to DirectLogin token="eyJhbGciOiJIUzI1NiIsInR5cCI6wkpeVeCJr.eyIiOiIifQ.MV-E150zMCrk6VrWv". You can do that like this:

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)
            }
    } 
}

...