微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

尝试获取访问令牌时出现Swift'Required String parameter'grant_type'not present'错误

如何解决尝试获取访问令牌时出现Swift'Required String parameter'grant_type'not present'错误

因此,我试图在Swift中制作一个应用程序,我需要登录该应用程序以登录OAuth以检索访问令牌。该API带有参数“ grant_type”和“ code”。

我尝试过:

let params = ["grant_type":"authorization_code","code":"123456789"] as Dictionary<String,String>

var request = URLRequest(url: URL(string: "https://myschool.zportal.nl/api/v3/oauth/token")!)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: params,options: [])
request.addValue("application/json",forHTTPHeaderField: "Content-Type")

let session = URLSession.shared
let task = session.dataTask(with: request,completionHandler: { data,response,error -> Void in
    do {
        let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary<String,AnyObject>
        print(json)
    } catch {
        print("error")
    }
})

task.resume()

这将返回:

["response": {
    data =     (
    );
    details = "class org.springframework.web.bind.MissingServletRequestParameterException: required String parameter 'grant_type' is not present";
    endRow = 0;
    eventId = 216795;
    message = "Internal problems.";
    startRow = 0;
    status = 500;
    totalRows = 0;
}]

这很奇怪,因为我确实将'grant_type'参数解析为正确的值。

它应该返回如下内容

{
  "response": {
    "status":200,"message":"","startRow":0,"endRow":27,"totalRows":27,"data":[
      {
      },...
    ]
  }
}

解决方法

标准消息格式需要表单URL编码的主体,而不是JSON。也许像this Swift article中那样修改您的代码。

,

使其正常工作:

@IBAction func sendButtonPressed(_ sender: UIButton) {

        let urlString = "https://myschool.zportal.nl/api/v3/oauth/token"
        performRequest(urlString: urlString)

    }
    
    func performRequest(urlString: String) {
        
        if let url = URL(string: urlString) {
            
            var request = URLRequest(url: url)
            request.httpMethod = "POST"
            request.httpBody = "grant_type=authorization_code&code=1234567890".data(using: .utf8)
            
            let session = URLSession(configuration: .default)
            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()
            
        }
        
    }

不是最好的代码,但我稍后会对其进行完善。 起初,我解析了JSON,但事实证明我需要解析一个String并将其转换为使用以下类型的数据类型:.data(using: .utf8)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。