gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 07:08:58 24 4
gpt4 key购买 nike

我正在尝试使用 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 请求中使用在特定端点上无效的方法。

如果您检查 documentation在 Spotify Web API 中,它明确指出用于 /me/tracks 端点的有效 HTTP 动词是:DELETEGETPUT。不允许 POST,因此出现错误。

只要把request.httpMethod = "post"改成request.httpMethod = "put",错误应该就解决了。

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

关于Swift Spotify API 错误代码 405 添加到库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46119001/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com