2016-09-19 101 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