发布到 Spotify API 以获得令牌返回状态 415。我是否遗漏了什么?

Posting to Spotify API for tokens is returning status 415. Am I missing something?

这是我为他们的授权代码流程点击他们的 API 的方法:

class func obtainAuthTokenPackage(authCode: String) throws
{
    //Create a request
    var request = URLRequest(url: Gimme.theSpotify.urlFor(endpoint: .requestingTokens)) //"https://accounts.spotify.com/api/token"
    request.httpMethod = "POST"

    //Build the header
    let spotifyClientCreds = Gimme.theSpotify.clientID + ":" + Gimme.theSpotify.clientSecret
    let encodedCreds = spotifyClientCreds.data(using: .utf8)!.base64EncodedString()
    request.setValue("Basic \(encodedCreds)", forHTTPHeaderField: "Authorization")
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")

    //Build the body
    var dict = [String:String]()
    dict["grant_type"] = "authorization_code"
    dict["code"] = authCode
    dict["redirect_uri"] = Gimme.theSpotify.redirectURI
    var package = Data()
    do
    {
        package = try JSONSerialization.data(withJSONObject: dict)
    }
    catch 
    {print("oopsie")}
    request.httpBody = package

    //Set up a web transaction
    let transaction = URLSession.shared.dataTask(with: request) {
        (possData, possResp, possErr) in
        if let data = possData
        {
            print(String(data: data, encoding: .utf8)!)
        }
    }
    //Do it
    transaction.resume()
}

靠近底部的打印语句产生 {"error":"server_error","error_description":"Unexpected status: 415"}

我已经尝试过的事情:

我有的问题:

谢谢大家的帮助。

我做到了!哈哈哈哈哈哈哈哈哈哈哈哈!!!!!!!!!!!!

//The endpoint expects form-urlencoded
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

//Build a string that has client_id, client_secret, grant_type, the code, and the redirect uri
//It has to be in that order (I didn't try any other order, but I've been having this problem for so long, I don't want to risk anything)
//It has to be in the form "key=value&key=value..." (Standard form url encoded format)
var formEncoded = "client_id=\(Gimme.theSpotify.clientID)"
formEncoded.append("&client_secret=\(Gimme.theSpotify.clientSecret)")
formEncoded.append("&grant_type=authorization_code")
formEncoded.append("&code=\(authCode)")
formEncoded.append("&redirect_uri=\(Gimme.theSpotify.redirectURI)")

//Finally convert it into UTF8 data
let bodyData = formEncoded.data(using: .utf8) //Check that this isn't nil, then proceed

//Stick this stuff in the transaction, and it'll be SUCCESSFULLLLL

我现在可以回答的问题:
- 此 api 端点 https://accounts.spotify.com/api/token application/x-www-form-urlencoded 作为 Content-Type.
- 我所做的不同之处:我在 body 中的 grant_type 密钥之前包含了客户端 ID 和客户端密码,而不是将其放在 header 中 - 如上面的代码段所示,我手动创建了 http body。

结论:
- 不需要什么花哨的东西
- 缺少 Spotify API 文档(但是来吧,谁不是?)
- 我松了口气