使用主体参数进行API调用

时间:2019-12-12 11:18:00

标签: ios json swift

我正在像这样进行API调用...(并且工作正常)

let url1 = URL(string: "https://clodsso.company.com/oauth2/access_token?AccessManagement")!
                var request = URLRequest(url: url1)
                request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
                request.addValue("application/json", forHTTPHeaderField: "Accept")
                let session = URLSession.shared
                request.httpMethod = "POST"
                let bodyStr = "grant_type=password&client_id=ASDH_HG&client_secret=768HJGLJfgfo879&username=A123456&password=passwordhyuhg&scope=shjDGH"

                request.httpBody = bodyStr.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue), allowLossyConversion: true)

                let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
                    guard error == nil else {
                        return
                    }
                    guard let data = data else {
                        return
                    }

                    do {

                        //create json object from data
                        if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {

                            print("Success resp :- \(json)")
                            // handle json...

                        }

                    } catch let error {

                        print("Failure resp : \(error.localizedDescription)")
                    }

  })
  task.resume()

现在,我想进行一个具有几个主体参数(即accessToken和Refresh令牌)的API调用。像这样在正文中(在POSTMAN中)给出

{
    "AccessToken":"hbvshiuevbkvbjdvkejbvk",
    "RefreshToken":"sfuhksdjfksjdhfksjdhf"
}

现在,当我也具有主体参数时,如何在这种情况下进行API调用?它类似于我上面给出的普通API调用吗?

2 个答案:

答案 0 :(得分:0)

我认为这应该是您想要的解决方案。

let body: [String : Any] = ["AccessToken" : "hbvshiuevbkvbjdvkejbvk", "RefreshToken" : "sfuhksdjfksjdhfksjdhf"]
request.httpBody = try? JSONSerialization.data(withJSONObject: body, options: .prettyPrinted)

答案 1 :(得分:0)

您可以简单地准备参数,使用 JSONSerialization 将其转换为数据并将该数据传递给 URLRequest httpBody 强>。您可以在项目中使用以下代码示例:

let params: [String: Any] = ["AccessToken": "hbvshiuevbkvbjdvkejbvk", "RefreshToken": "sfuhksdjfksjdhfksjdhf"]

guard let data = try? JSONSerialization.data(withJSONObject: params, options: .prettyPrinted) else {return}

request.httpBody = data