简体   繁体   English

使用HTTParty在JSON POST请求中发送数组

[英]Send array in JSON POST request with HTTParty

I'm trying to work with a 3rd party API that requires an array to be sent within a POST request body. 我正在尝试使用需要在POST请求正文中发送数组的第三方API。 I've already gotten the hang of sending JSON; 我已经掌握了发送JSON的窍门; I've read you just need to set some headers and call to_json on the POST body. 我读过您只需要设置一些标头并在POST主体上调用to_json However, I'm not sure how to embed an array within that POST body. 但是,我不确定如何在该POST正文中嵌入数组。 I've tried the following: 我尝试了以下方法:

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

but this is giving me a server error, leading me to believe the array isn't being formatted correctly. 但这给了我一个服务器错误,使我相信阵列的格式不正确。 Could someone please advise on how to send an array within a JSON POST request? 有人可以建议如何在JSON POST请求中发送数组吗? Thanks! 谢谢!

EDIT: 编辑:

The error I get back is the following: 我得到的错误如下:

#<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"]}> 

The JSON should be in the format: JSON的格式应为:

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

The simplest way to embed an array within a POST body using HTTParty in Ruby on Rails is to pass the request to an instance variable (any name of your choice can suffice for the instance variable). 在Ruby on Rails中使用HTTParty在POST主体中嵌入数组的最简单方法是将请求传递给实例变量(您选择的任何名称都可以满足该实例变量的要求)。

So we will have 所以我们将有

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

Here is an example of an HTTParty Post Request 这是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'})

That's all 就这样

I hope this helps. 我希望这有帮助。

I had a similar requirement for a SurveyMonkey API, the below will create a params_hash with nested array of hashes 我对SurveyMonkey API有类似的要求,下面将创建带有嵌套哈希数组的params_hash

create the fields array of hashes 创建哈希的字段数组

fields = []

i =0

while i < 10 do

fields << {":id#{i}" => "some value #{i}"}

i += 1

end

method with optional splat field variable 可选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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM