【问题标题】:Send array in JSON POST request with HTTParty使用 HTTParty 在 JSON POST 请求中发送数组
【发布时间】:2014-10-07 07:16:35
【问题描述】:

我正在尝试使用需要在 POST 请求正文中发送数组的第 3 方 API。我已经掌握了发送 JSON 的窍门;我读过你只需要设置一些标题并在 POST 正文上调用 to_json。但是,我不确定如何在该 POST 正文中嵌入一个数组。我尝试了以下方法:

HTTParty.post(url, 
    :body => { 
        :things => [{:id => 1}, {:id => 2}, {:id => 3}],
    }.to_json,
    :headers => { 
        'Content-Type' => 'application/json', 
        'Accept' => 'application/json'
    }
)

但这给了我一个服务器错误,让我相信数组的格式不正确。有人可以建议如何在 JSON POST 请求中发送数组吗?谢谢!

编辑:

我得到的错误如下:

#<HTTParty::Response:0x10 parsed_response=nil, 
@response=#<Net::HTTPInternalServerError 500 Internal Server Error readbody=true>, 
@headers={"error_message"=>["Can not deserialize instance of java.lang.Long out of 
START_OBJECT token  at [Source: org.apache.catalina.connector.CoyoteInputStream@30edd11c; 
line: 1, column: 15] (through reference chain: REDACTED[\"things\"])"], 
"error_code"=>["0"], "content-length"=>["0"], 
"date"=>["Wed, 13 Aug 2014 22:53:49 GMT"], "connection"=>["close"]}> 

JSON 格式应为:

{ "things" : [ {"id": "..."}, {"id: "..."}, ... ] }

【问题讨论】:

  • 您的代码在我看来总体上没问题。 JSON 将是有效的(并且将包含一个数组),但您可能没有以 API 的正确结构发送数据。您能否提供参考或来自 API 文档的正确示例 JSON?另外,如果相关,请提供服务器错误消息。
  • 我已经按照您的要求更新了帖子!还稍微更改了我的代码,因为我第一次犯了错误。
  • 密钥:myid 是故意的和必需的吗?它与您的示例 JSON 不匹配。
  • 我的错,这是一个错字。但与问题无关。
  • 这个 SO answer 可能会有所帮助。看起来 HTTParty 默认使用 HashConversions 来规范化请求。尝试使用 HTTParty.query_string_normalizer 覆盖数组的这种行为。

标签: ruby-on-rails ruby json httparty


【解决方案1】:

在 Ruby on Rails 中使用 HTTParty 在 POST 正文中嵌入数组的最简单方法是将请求传递给实例变量(您选择的任何名称都可以用于实例变量)。

所以我们会有

@mypost = HTTParty.post(url, 
         :body => { 
                    :things => {
                       :id => 1, 
                       :id => 2,
                       :id => 3
                    },
                  }.to_json,
         :headers => { 
                    'Content-Type' => 'application/json',
                    'Authorization' => 'xxxxxxxxxx' 
                    'Accept' => 'application/json'
                    })

这是 HTTParty 发布请求的示例

 @myrequest = HTTParty.post(' https://www.pingme.com/wp-json/wplms/v1/user/register',
            :body => {
                        :books => {  
                          :name => "#{@book.name}",
                          :author => "#{@book.author}",
                          :description => "#{@book.description}",
                          :category_id => "#{@book.category_id}",
                          :sub_category_id => "#{@book.sub_category_id}"
                        },
                      }.to_json, 
            :headers => { 'Content-Type' => 'application/json', 
                          'Authorization' => '77d22458349303990334xxxxxxxxxx',
                          'Accept' => 'application/json'})

就是这样

我希望这会有所帮助。

【讨论】:

    【解决方案2】:

    我对 SurveyMonkey API 有类似的要求,下面将创建一个带有嵌套哈希数组的 params_hash

    创建哈希字段数组

    fields = []
    
    i =0
    
    while i < 10 do
    
    fields << {":id#{i}" => "some value #{i}"}
    
    i += 1
    
    end
    

    带有可选 splat 字段变量的方法

    def get_response(survey_id, respondent_ids, *fields )
    
      params_hash = {}
    
      params_hash[:survey_id] = "#{survey_id}"
    
      params_hash[:respondent_ids] = respondent_ids
    
      params_hash[:fields] = fields
    
      @result = HTTParty.post("http://"some.address.here",
    
        #:debug_output => $stdout,
    
        :headers => {'Authorization' => "bearer #{@access_token.to_s}", 'Content-type' => 'application/json'},
    
      :body => params_hash.to_json,
    
      )
    
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-18
      • 1970-01-01
      • 2016-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多