【发布时间】:2017-03-04 12:19:03
【问题描述】:
我正在尝试为我的项目调用外部 API,但在我的 rails lib 中使用 Net::HTTP 时遇到了一些麻烦。这是我的代码
class ApiCall
def self.do_api_request(api_token, body)
require 'net/http'
require 'uri'
uri = URI.parse('https://sample.com')
header = {'Token' => api_token, 'Content-Type' => 'application/json', 'Accept' => 'application/json'}
request = Net::HTTP::Post.new(uri.request_uri, header)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = (uri.scheme == "https")
request.body = body
http.request(request)
end
end
这就是我使用它的方式(假设我知道api_token 和body):
body = {'id' => 2, 'age'=> 23};
ApiCall.do_api_request(api_token, body)
这样,它会抛出一个错误:
NoMethodError: Hash 的未定义方法 `bytesize'
然后在网上查了一下,好像正文是哈希而不是字符串,所以我这样做了
body = URI.encode_www_form(body) 重新运行后,它给了我:
400 错误请求
我不知道如何将 header 和 body 放入 rails Net::HTTP 方法
解决方案:
我知道问题出在哪里。 request body 应该是 string
所以body = "{'id' : 2, 'age' : 23}",我用body.to_json
【问题讨论】:
标签: ruby-on-rails ruby