问题
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