在ruby中重现curl请求

时间:2016-04-28 15:59:39

标签: ruby curl

我有下一个卷曲请求:

curl -X POST -H "Content-Type: application/json" -H "charset: UTF-8" -H "Cache-Control: no-cache" -d '{"destId":684}' https://viatorapi.viator.com/service/search/products?apiKey=VIATOR_API_KEY

这个卷曲请求工作正常。如果我尝试将 apiKey 参数移动到数据哈希,我会收到apiKey缺失的错误。例如

curl -X POST -H "Content-Type: application/json" -H "charset: UTF-8" -H "Cache-Control: no-cache" -d '{"destId":684, "apiKey":VIATOR_API_KEY}' https://viatorapi.viator.com/service/search/products

我无法理解这两个请求之间的区别。

显然,我使用的是真正的价值而不是VIATOR_API_KEY。

现在我正试图在ruby中重现这个卷曲请求。

require 'uri'
require 'net/http'
require 'json'

API_KEY        = ENV['VIATOR_API_KEY']
BASE_URL       = "http://viatorapi.viator.com/service"
path           = "/search/products"

# Full reference
uri = URI.parse "#{BASE_URL}#{path}?apiKey=#{API_KEY}"

http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri)
request.initialize_http_header({"Content-type" => "application/json", "charset" => "UTF-8", "Cache-Control" => "no-cache"})
request.set_form_data('destId' => 684)

response = http.request(request)

puts response.body

if response.code == "200"
  # Do something
end

现在我收到415错误不支持的媒体类型

任何想法可能是什么问题?

更新

我已经弄清楚它到底是什么了。 在设置数据参数之前request.set_form_data('destId' => 684) 请求标题是

{"content-type"=>["application/json"], "charset"=>["UTF-8"], "cache-control"=>["no-cache"]}

{"content-type"=>["application/x-www-form-urlencoded"], "charset"=>["UTF-8"], "cache-control"=>["no-cache"]}

所以,不知怎的,set_form_data改变了内容类型

3 个答案:

答案 0 :(得分:4)

我认为你可以使用gem Typhoeus是一个curl包装器,很容易翻译curl请求,这里是你的请求的例子

require 'typhoeus'

request = Typhoeus::Request.new(
  "https://viatorapi.viator.com/service/search/products",
  method: :post,
  params: { apiKey: "VIATOR_API_KEY" },
  body: { destId: 684},
  headers: { 'Content-Type' => "application/json", charset: "UTF-8",'Cache-Control' => "no-cache" }
)

request.on_complete do |response|
  if response.success?
    # hell yeah
  elsif response.timed_out?
    # aw hell no
    log("got a time out")
  elsif response.code == 0
    # Could not get an http response, something's wrong.
   log(response.return_message)
  else
    # Received a non-successful http response.
    log("HTTP request failed: " + response.code.to_s)
  end
end

request.run

#curl -X POST -H "Content-Type: application/json" -H "charset: UTF-8" -H "Cache-Control: no-cache" -d '{"destId":684}' https://viatorapi.viator.com/service/search/products?apiKey=VIATOR_API_KEY
执行

irb(main):112:0' => #<Typhoeus::Response:0x007fd46396b920 @options={:httpauth_avail=>0, :total_time=>0.933899, :starttransfer_time=>0.93374, :appconnect_time=>0.52442, :pretransfer_time=>0.5244530000000001, :connect_time=>0.25838099999999997, :namelookup_time=>0.000657, :redirect_time=>0.0, :effective_url=>"https://viatorapi.viator.com/service/search/products?apiKey=VIATOR_API_KEY", :primary_ip=>"54.165.220.73", :response_code=>200, :request_size=>269, :redirect_count=>0, :return_code=>:ok, :response_headers=>"HTTP/1.1 200 OK\r\nDate: Thu, 28 Apr 2016 17:24:23 GMT\r\nContent-Type: application/json;charset=ISO-8859-1\r\nContent-Length: 372\r\nVary: Accept-Encoding\r\n\r\n", :response_body=>"{\"errorReference\":\"~21084218484370761736807418\",\"data\":null,\"dateStamp\":\"2016-04-28T10:24:23+0000\",\"errorType\":\"EXCEPTION\",\"errorMessage\":[\"API ACCESS DENIED!!! Api Key 'VIATOR_API_KEY' is invalid or missing\"],\"errorName\":\"Exception\",\"success\":false,\"totalCount\":1,\"vmid\":\"331004\",\"errorMessageText\":[\"API ACCESS DENIED!!! Api Key 'VIATOR_API_KEY' is invalid or missing\"]}", :debug_info=>#<Ethon::Easy::DebugInfo:0x007fd463988ca0 @messages=[]>}, @request=#<Typhoeus::Request:0x007fd464810f98 @base_url="https://viatorapi.viator.com/service/search/products", @original_options={:method=>:post, :params=>{:apiKey=>"VIATOR_API_KEY"}, :body=>{:destId=>684}, :headers=>{"Content-Type"=>"application/json", :charset=>"UTF-8", "Cache-Control"=>"no-cache"}}, @options={:method=>:post, :params=>{:apiKey=>"VIATOR_API_KEY"}, :body=>{:destId=>684}, :headers=>{"User-Agent"=>"Typhoeus - https://github.com/typhoeus/typhoeus", "Content-Type"=>"application/json", :charset=>"UTF-8", "Cache-Control"=>"no-cache"}, :maxredirs=>50}, @response=#<Typhoeus::Response:0x007fd46396b920 ...>, @on_headers=[], @on_complete=[#<Proc:0x007fd464810e58@/Users/toni/learn/ruby/stackoverflow/scripting/typhoeus_request.rb:11>], @on_success=[]>, @handled_response=nil>
    irb(main):113:0> 

有点漂亮

irb(main):039:0> require 'yaml'
=> true
irb(main):043:0> puts request.response.to_yaml
--- &3 !ruby/object:Typhoeus::Response
options:
  :httpauth_avail: 0
  :total_time: 0.6263529999999999
  :starttransfer_time: 0.6262380000000001
  :appconnect_time: 0.264124
  :pretransfer_time: 0.264161
  :connect_time: 0.131438
  :namelookup_time: 0.00059
  :redirect_time: 0.0
  :effective_url: https://viatorapi.viator.com/service/search/products?apiKey=VIATOR_API_KEY
  :primary_ip: 54.165.220.73
  :response_code: 200
  :request_size: 269
  :redirect_count: 0
  :return_code: :ok
  :response_headers: "HTTP/1.1 200 OK\r\nDate: Fri, 29 Apr 2016 06:25:36 GMT\r\nContent-Type:
    application/json;charset=ISO-8859-1\r\nContent-Length: 371\r\nVary: Accept-Encoding\r\n\r\n"
  :response_body: '{"errorReference":"~2155052986177618334013969","data":null,"dateStamp":"2016-04-28T23:25:36+0000","errorType":"EXCEPTION","errorMessage":["API
    ACCESS DENIED!!! Api Key ''VIATOR_API_KEY'' is invalid or missing"],"errorName":"Exception","success":false,"totalCount":1,"vmid":"331009","errorMessageText":["API
    ACCESS DENIED!!! Api Key ''VIATOR_API_KEY'' is invalid or missing"]}'
  :debug_info: !ruby/object:Ethon::Easy::DebugInfo
    messages: []
request: !ruby/object:Typhoeus::Request
  base_url: https://viatorapi.viator.com/service/search/products
  original_options:
    :method: :post
    :params: &1
      :apiKey: VIATOR_API_KEY
    :body: &2
      :destId: 684
    :headers:
      Content-Type: application/json
      :charset: UTF-8
      Cache-Control: no-cache
  options:
    :method: :post
    :params: *1
    :body: *2
    :headers:
      User-Agent: Typhoeus - https://github.com/typhoeus/typhoeus
      Content-Type: application/json
      :charset: UTF-8
      Cache-Control: no-cache
    :maxredirs: 50
  on_complete:
  - !ruby/object:Proc {}
  on_headers: []
  response: *3
  on_success: []
handled_response: 
=> nil

答案 1 :(得分:0)

我无法找到该网站的API文档,但似乎端点期望apiKey是url查询参数,而不是在有效负载中。

答案 2 :(得分:0)

如果你想坚持使用纯Ruby和Net::HTTP,那么我建议requestsNet::HTTP上的一个包装,它可以很容易地发送请求。