错误405:无法上传自定义播放列表封面图像

时间:2018-07-20 15:06:20

标签: spotify nsmutableurlrequest

我想将播放列表图像从iOS应用程序上传到Spotify Web API。

我遵循了docs page上的指示:我请求了ugc-image-uploadplaylist-modify-publicplaylist-modify-private范围,添加了内容类型标头,并制作了一个jpeg Base64字符串。但是我一直在找回405 Method Not Allowed错误。我可以在Android上使用相同的URL和授权令牌创建图像。我已经尝试将android生成的Base64字符串添加到我的swift请求中,但这也不起作用。

这是Postman生成的快速代码示例,我在其中尝试调试此请求。 Base64字符串是一个100x100的橙色jpeg图像,它是在我的android应用中生成并在其中工作的。解码过程确实可以在该站点上进行,结果是预期的图像:https://www.base64decode.org在Postman中,我也无法使它正常工作。

let headers = [
    "Authorization": "Bearer […]",
    "Content-Type": "image/jpeg",
    "Cache-Control": "no-cache"
]

let postData = NSData(data: "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCABkAGQDASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAj/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFgEBAQEAAAAAAAAAAAAAAAAAAAkK/8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AvABJ9oAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAf/9k=".data(using: String.Encoding.utf8)!)

let request = NSMutableURLRequest(url: NSURL(string: "https://api.spotify.com/v1/users/[…]/playlists/[…]/images")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
    if (error != nil) {
        print(error)
    } else {
        let httpResponse = response as? HTTPURLResponse
        print(httpResponse)
    }
})

dataTask.resume()

这是httpResponse

Optional(<NSHTTPURLResponse: 0x282fdf300> { URL: https://api.spotify.com/v1/users/[…]/playlists/[…]/images } { Status Code: 405, Headers {
    "Access-Control-Allow-Origin" =     (
        "*"
    );
    "Cache-Control" =     (
        "private, max-age=0"
    );
    "Content-Length" =     (
        0
    );
    Date =     (
        "Fri, 20 Jul 2018 14:12:01 GMT"
    );
    Via =     (
        "1.1 google"
    );
    "access-control-allow-credentials" =     (
        true
    );
    "access-control-allow-headers" =     (
        "Accept, Authorization, Origin, Content-Type, Retry-After"
    );
    "access-control-allow-methods" =     (
        "GET, POST, OPTIONS, PUT, DELETE, PATCH"
    );
    "access-control-max-age" =     (
        604800
    );
    allow =     (
        "GET, HEAD, OPTIONS, PUT"
    );
    "alt-svc" =     (
        clear
    );
} })

由于Base64字符串,授权令牌和URL相同,因此我认为我的请求正文或标头字段有问题。

提前谢谢!

1 个答案:

答案 0 :(得分:0)

发现了问题:它应该执行PUT请求而不是POST请求。 更改这一行后,它确实起作用了。

request.httpMethod = "PUT"