我需要從Spotify Web API獲取訪問令牌。基於this documentation我寫了下面方法:Spotify Web API:基本授權
def authorize
grant = Base64.encode64("#{SPOTIFY_KEY}:#{SPOTIFY_SECRET}")
RestClient::Request.execute(
method: :post,
url: 'https://accounts.spotify.com/api/token',
params: {'grant_type' => 'client_credentials'},
headers: {"Authorization" => "BasiC#{grant}","Accept" => "*/*; q=0.5, application/json"}
)
end
和以下RSpec的測試:
it 'authorize' do
obj = SpotifyIntegration.new
response = obj.authorize
myjson = JSON.parse(response.body)
expect(myjson.has_key?('access_token')).to be(true)
expect(myjson.has_key?('token_type')).to be(true)
expect(myjson['token_type']).to eq('bearer')
expect(myjson.has_key?('expires_in')).to be(true)
end
它發生的是,當我運行該測試中,生成該請求(補時RESTCLIENT_LOG = STDOUT)
RestClient.post 「https://accounts.spotify.com/api/token」, 「接受」=> 「/; q = 0.5,應用/ JSON」, 「接受編碼」=> 「的gzip,放氣」,「A uthorization 「=>」 基本Y2NmNTI3ODVlZWI1NDVlODk0ZmM2ZTY3YTZhNDM0ZDA6YTQ5MjdlOGFmOWQy \ nNGE0OTgyZDRkODI1MmJhZjBkNTI = \ n」
我得到
=> 400錯誤請求|應用程序/ json 131字節
而且它似乎確實是一個不好的請求,因爲我看不到grant_type => client_credentials
的跡象。文檔說這是作爲請求主體參數的mandadory 。
我相信我發送這個錯誤的方式,但我不知道如何正確。
我試圖用RestClient#post
代替RestClient::Request#execute
,這樣做:
def authorize
grant = Base64.encode64("#{SPOTIFY_KEY}:#{SPOTIFY_SECRET}")
RestClient.post 'https://accounts.spotify.com/api/token', {'grant_type' => 'client_credentials'}.to_json, {"Authentication" => "BasiC#{grant}",content_type: :json, accept: :json}
end
,但後來我:
RESTClient實現:: UnsupportedMediaType: 415不支持的媒體類型
我如何使用RestClient
寶石發送請求身體參數?
當然可以。我做到了。用'{'grant_type'=>'client_credentials'}'我得到一個'400 Bad Request'。如果我使用'{'grant_type'=>'client_credentials'}。to_json'來完成,我在一些參考文獻中找到了'415 Unsupported Media Type' ... –
同意,@Anthony。這就是爲什麼我驚訝它不起作用。真的不知道該怎麼做。 –