我正在使用Spotify Web API在Rails中构建应用程序。我建立了一种刷新用户令牌的方法,但收到400错误。根据Spotify Web API文档,我请求的标头必须采用以下格式:
Authorization: Basic <base64 encoded client_id:client_secret>
使用Httparty gem,以下是POST方法来刷新访问令牌:
def refresh_token
client_id = "foo"
client_secret = "bar"
client_id_and_secret = Base64.encode64("#{client_id}:#{client_secret}")
result = HTTParty.post(
"https://accounts.spotify.com/api/token",
:body => {:grant_type => "refresh_token",
:refresh_token => "#{self.oauth_refresh_token}"},
:headers => {"Authorization" => "Basic #{client_id_and_secret}"}
)
end
这就是“结果”的最终结果:
=> #<HTTParty::Response:0x7f92190b2978 parsed_response={"error"=>"invalid_client", "error_description"=>"Invalid client secret"}, @response=#<Net::HTTPBadRequest 400 Bad Request readbody=true>, @headers={"server"=>["nginx"], "date"=>["Sun, 31 Aug 2014 22:28:38 GMT"], "content-type"=>["application/json"], "content-length"=>["70"], "connection"=>["close"]}>
我可以解码client_id_and_secret,它返回“ foo:bar”,所以我不知道为什么收到400错误。非常感谢任何见解。
发现了问题...是Ruby中的Base64编码引起的。显然(如Ruby中base64编码字符串中的Strange \ n所示),使用Base64.encode64('')方法在代码内增加了一行。使用Base64.strict_encode64('')解决了这个问题。
更新的代码:
def refresh_token
client_id = "foo"
client_secret = "bar"
client_id_and_secret = Base64.strict_encode64("#{client_id}:#{client_secret}")
result = HTTParty.post(
"https://accounts.spotify.com/api/token",
:body => {:grant_type => "refresh_token",
:refresh_token => "#{self.oauth_refresh_token}"},
:headers => {"Authorization" => "Basic #{client_id_and_secret}"}
)
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句