【问题标题】:Net/HTTP in rails with request header and body带有请求标头和正文的 Rails 中的 Net/HTTP
【发布时间】: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_tokenbody):

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


    【解决方案1】:

    我会建议你使用HTTParty 来调用一个api。这使用起来非常简单。以下是示例-

    HTTParty.get("https://api.bigcommerce.com/stores/"+@store.store_hash+"/v3/catalog/categories", :headers => @your_header_data)
    

    这将返回响应。也用于发布请求,

    HTTParty.post("https://api.bigcommerce.com/stores/"+@store.store_hash+"/v3/catalog/products", :headers => @auth, :body => product_json)
    

    所以你可以在这里将 body 传递给 in body 参数。

    【讨论】:

      猜你喜欢
      • 2020-12-23
      • 1970-01-01
      • 2021-09-11
      • 1970-01-01
      • 2018-12-06
      • 2022-01-23
      • 1970-01-01
      • 2019-05-29
      • 2019-12-13
      相关资源
      最近更新 更多