簡體   English   中英

使用HTTParty在JSON POST請求中發送數組

[英]Send array in JSON POST request with HTTParty

我正在嘗試使用需要在POST請求正文中發送數組的第三方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: "..."}, ... ] }

在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'})

就這樣

我希望這有幫助。

我對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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM