使用bearer token发布请求并获取访问令牌以响应ruby

时间:2018-01-29 06:33:34

标签: ruby-on-rails ruby http-post bearer-token net-http

我可以访问带有持票人令牌的API,并且我在INSOMNIA / Postman工具中获得了以下值的响应:

m

但是,当我试图从红宝石脚本中获取相同的内容时,我只能将响应代码设置为200OK,如下所示:

{
    "access_token": "ki1AH9hiF8_OTGr70VnOnb-I7ZRWVI3u6pXxWHW6hStckd3WC3NLviN0Z036dvBVfEQFWO691t-9roX-p1w6gou1TlWAqEwX3mmLwcZ4VcwrS5YWY8GLSxjBCSMdcn5RLBPfh5jubNX8_vrrX3D3bTbsGnxE1jeWf_T-lnUGEkWz876o3kbonIFWwJMO8-athkcfb3kPoqOrD1w2CRyeDADFvYuPiTpbiG75a9s1V-qdgTGdYaP8-FRnm0G0zhKt8lQo2W8pBBa4dMv-5jQSEA",
    "token_type": "bearer",
    "expires_in": 14399
}

我已经写了下面的rake任务来获取发布请求的响应中的访问令牌:

[1] pry(main)> response = http.request(request)
=> #<Net::HTTPOK 200 OK readbody=true>

请帮助我获取access_token以响应我在Postman或Insomnia工具中看到的帖子请求。

通过rake任务,我只获得200OK状态代码。

require "net/http" require "uri" desc "post request and get response" task :post_request_and_get_response => :environment do uri = URI.parse("my_url") http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(uri.request_uri) request["Authorization"] = 'Bearer token' request["Content-Type"] = 'application/x-www-form-urlencoded' request.set_form_data({"grant_type" => "password", "username" => "user", "password" => "my_password"}) p response = http.request(request) end 我只获取以下值而不是access_token

response.body

提前致谢。

1 个答案:

答案 0 :(得分:1)

您可以获取响应正文并将其解析为JSON代码:

require 'JSON'

body = response.body
data = JSON.parse body
puts data['access_token']

希望它有所帮助。 enter image description here