Swift Spotify API 错误代码 405 添加到音乐库?

Swift Spotify API Error code 405 add to library?

我正在尝试使用 Spotify API 将 Track 添加到用户的音乐库,但我收到 400 响应状态。我已经用 Alamofire 尝试了这个请求并开始收到 postCount 错误,因为 Spotify header 令牌 ..

这是代码的一部分:

func spotify_addToLibrary()
{

    self.spotify_verifySession(completion:{ success , auth in

        if !success
        {
            return
        }

        let postString                  = "ids=[\"\(self.trackid)\"]"
        let url: NSURL                  = NSURL(string: "https://api.spotify.com/v1/me/tracks")!
        var request                     = URLRequest(url: url as URL)
            request.cachePolicy         = .useProtocolCachePolicy
            request.timeoutInterval     = 8000
            request.addValue("application/x-www-form-urlencoded;charset=UTF-8", forHTTPHeaderField: "Content-Type")
            request.addValue("application/json", forHTTPHeaderField: "Accept")
            request.addValue("Bearer \(auth.session.accessToken!)", forHTTPHeaderField: "Authorization")
            request.httpMethod = "post"
            request.httpBody   = postString.data(using: .utf8)

         URLSession.shared.dataTask(with: request) {data, response, err in

                    if err == nil
                    {
                        print("Add to Library success \(String(describing: response))")

                    }else
                    {
                        print("Add to Library Error \(String(describing: err))")
                    }

                }.resume()
    })
}

这是日志:

Add to Library success Optional(<NSHTTPURLResponse: 0x174c25d80> { URL: https://api.spotify.com/v1/me/tracks } { status code: 405, headers {
    "Access-Control-Allow-Origin" = "*";
    "Cache-Control" = "private, max-age=0";
    "Content-Length" = 0;
    Date = "Fri, 08 Sep 2017 14:29:24 GMT";
    Server = nginx;
    "access-control-allow-credentials" = true;
    "access-control-allow-headers" = "Accept, Authorization, Origin, Content-Type";
    "access-control-allow-methods" = "GET, POST, OPTIONS, PUT, DELETE";
    "access-control-max-age" = 604800;
    allow = "DELETE, GET, HEAD, OPTIONS, PUT";
} })

我错过了什么?

HTTP 错误 405 表示您正尝试在 REST 请求中使用在特定端点上无效的方法。

如果您检查 Spotify Web documentation API,它清楚地指出要用于 /me/tracks 端点的有效 HTTP 动词是:DELETE , GETPUT。不允许 POST,因此出现错误。

request.httpMethod = "post"改成request.httpMethod = "put"就可以解决错误

一些一般性建议:当原生 Swift 等价物存在时(NSURL 而不是 URL)不要使用 Foundation 类型并且符合 Swift 命名约定,变量和函数名称采用小驼峰命名法(spotify_addToLibrary 应为 spotifyAddToLibrary)。 8000的超时间隔似乎也很不现实。