2016-09-19 105 views
0

我正嘗試使用HTTParty連接到一些API。首先,我需要使用我的憑證登錄才能獲取令牌,之後我需要使用此令牌進行其他獲取請求。使用HTTParty post連接到第三方API並獲取,Ruby

當我這樣做:

def get_token 
    HTTParty.post(base_url + '/login', headers: { "Content-Type": "application/json" }, body: body_hash).body 
end 

其中

def body_hash 
    { 
     "username": "my_username", 
     "apikey": "7867868yiuhi76" 
    }.to_json 
end 

,並與我正確地接收令牌。

然後我嘗試做得到一個不同的URL上像這樣的API:

response = JSON.parse(get_token)    
data = HTTParty.get(base_url + '/some_path', headers: { "Content-Type": "application/json", "Authorization: Bearer" => response['token'] }).body 
puts data 

,我得到錯誤:

"Internal server error" 

有誰知道什麼可能是這裏的問題?謝謝。

+0

能否請您提供有關您正在使用的API的更多信息? –

+0

嘗試標題爲'{「Content-Type」:「application/json」,「Authorization」:「Bearer」+ response ['token']}' – Anthony

+0

@Anthony以這種方式更改標題,謝謝! – user1993565

回答

0

你只是在頭文件中混合了參數。假設這是Oauth/Oauth2,您需要發送'授權'鍵以'值持有人令牌'。

因此,對於你的例子:

HTTParty.get(base_url + '/some_path', headers: { "Content-Type": "application/json", "Authorization": "Bearer #{response['token']}" }).body