How to convert CURL request to Swift using Alamofire?

穿精又带淫゛_ 提交于 2021-02-08 03:12:41

问题


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.

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?

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

回答1:


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

...


来源:https://stackoverflow.com/questions/53249317/how-to-convert-curl-request-to-swift-using-alamofire

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!