【问题标题】:Using Ruby's Net/HTTP module, can I ever send raw JSON data?使用 Ruby 的 Net/HTTP 模块,我可以发送原始 JSON 数据吗?
【发布时间】:2016-08-22 07:52:48
【问题描述】:

与通过 Fiddler 发送数据和请求相比,我一直在对通过 Ruby HTTP 请求发送 JSON 数据的主题进行大量研究。 我的主要目标是找到一种使用 Ruby 在 HTTP 请求中发送嵌套数据散列的方法。

在 Fiddler 中,您可以在请求正文中指定 JSON 并添加标头“Content-Type: application/json”。

在 Ruby 中,使用 Net/HTTP,如果可能的话,我想做同样的事情。我有一种预感,这是不可能的,因为在 Ruby 中将 JSON 数据添加到 http 请求的唯一方法是使用 set_form_data,它需要散列中的数据。在大多数情况下这很好,但是这个函数不能正确处理嵌套哈希(参见本文中的comments)。

有什么建议吗?

【问题讨论】:

    标签: ruby json httprequest net-http


    【解决方案1】:

    虽然使用像 Faraday 这样的东西通常更令人愉快,但它仍然可以使用 Net::HTTP 库:

    require 'uri'
    require 'json'
    require 'net/http'
    
    url = URI.parse("http://example.com/endpoint")
    
    http = Net::HTTP.new(url.host, url.port)
    
    content = { test: 'content' }
    
    http.post(
      url.path,
      JSON.dump(content),
      'Content-type' => 'application/json',
      'Accept' => 'text/json, application/json'
    )
    

    【讨论】:

      【解决方案2】:

      在阅读了上面 tadman 的回答后,我更仔细地研究了将数据直接添加到 HTTP 请求的正文中。最后,我确实做到了:

      require 'uri'
      require 'json'
      require 'net/http'
      
      jsonbody = '{
                   "id":50071,"name":"qatest123456","pricings":[
                    {"id":"dsb","name":"DSB","entity_type":"Other","price":6},
                    {"id":"tokens","name":"Tokens","entity_type":"All","price":500}
                    ]
                  }'
      
      # Prepare request
      url = server + "/v1/entities"
      uri = URI.parse(url)  
      http = Net::HTTP.new(uri.host, uri.port)
      http.set_debug_output( $stdout )
      
      request = Net::HTTP::Put.new(uri )
      request.body = jsonbody
      request.set_content_type("application/json")
      
      # Send request
      response = http.request(request)
      

      如果您想调试发出的 HTTP 请求,请使用以下代码,逐字逐句:http.set_debug_output($stdout)。这可能是调试通过 Ruby 发送的 HTTP 请求的最简单方法,并且非常清楚发生了什么:)

      【讨论】:

        猜你喜欢
        • 2015-06-04
        • 2014-12-20
        • 1970-01-01
        • 2020-12-24
        • 1970-01-01
        • 1970-01-01
        • 2019-10-12
        • 2015-10-21
        • 2013-06-27
        相关资源
        最近更新 更多