I would like to receive a token using http post based on the image below. I wrote it like the bottom code, but it doesn't work well. What should I do?
func login() {
let username = "TestID"
let password = "TestPW"
let loginString = "\(username):\(password)"
guard let loginData = loginString.data(using: String.Encoding.utf8) else {
return
}
let base64LoginString = loginData.base64EncodedString()
let param = "id=0000&password=1234&password2=1234&grantType=password"
let paramData = param.data(using: .utf8)
var request = URLRequest(url: URL(string: "https://TestUrl.com")!)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
request.setValue(String(paramData!.count), forHTTPHeaderField: "Content-Length")
request.httpBody = paramData
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
print(response!)
do {
let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary<String, AnyObject>
print(json)
} catch {
print("error")
}
})
task.resume()
}
Based on image of the API, it looks like you re sending Authentication
header correctly. However it seems the body data is expected as JSON object:
{
"id": 0000,
"password": 1234,
"password2": 1234,
"gratType": "password"
}
So you need to create a Codable
structure:
struct LoginData: Codable {
let id: Int
let password: Int
let password2: Int
let gratType: String
}
And then you convert it to JSON:
let loginData = LoginData(id: 0, password: 1234, password2: 1234, gratType: "password")
request.httpBody = try JSONEncoder().encode(loginData)
Note that I created this structure based on your example, which shows id
, password
and password2
fields as numeric fields (not Strings), which is a bit weird to me, I would expect at least password fields to be Strings. Also gratType
is potentially misspelled (should be grantType
?). But that's something you can adjust later.