pat*_*kil 3 ruby-on-rails spotify httparty
我正在使用Spotify Web API在Rails中构建应用程序.我构建了一个刷新用户令牌的方法,但收到400错误.根据Spotify Web API文档,我的请求标题需要采用以下格式:
Authorization: Basic <base64 encoded client_id:client_secret>
Run Code Online (Sandbox Code Playgroud)
使用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
Run Code Online (Sandbox Code Playgroud)
以下是"结果"最终结果:
=> #<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"]}>
Run Code Online (Sandbox Code Playgroud)
我可以解码client_id_and_secret并返回"foo:bar",所以我不知道为什么我收到400错误.任何见解都非常感谢.
pat*_*kil 14
发现了这个问题......它使用的是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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2671 次 |
| 最近记录: |