我正在尝试使用Spotify API将Track添加到用户库,我收到错误400,我已经使用Alamofire
尝试了此请求,并因postCount
而误报Spotify
标头令牌..
这是代码的一部分:
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()
})
}
这是Log:
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";
} })
我在那里想念的是什么?
答案 0 :(得分:2)
HTTP错误405表示您尝试在REST请求中使用在特定端点上无效的方法。
如果您查看Spotify Web API的documentation,则会明确指出要用于/me/tracks
端点的有效HTTP谓词为:DELETE
,GET
和PUT
。不允许POST
,因此错误。
只需将request.httpMethod = "post"
更改为request.httpMethod = "put"
即可解决错误。
一些通用建议:当存在本机Swift等价物时,不要使用Foundation
类型(NSURL
而不是URL
)并且符合Swift命名约定,这是较低的camelCase for变量和函数名称(spotify_addToLibrary
应为spotifyAddToLibrary
)。超时间隔为8000 秒似乎也是不切实际的。