2017-01-13 43 views
0

我必須在httparty發送POST請求並得到響應 的json PARAMS是如何構建JSON PARAMS在Httparty

{ 
    "webhook": { 
    "topic": "shop/update", 
    "address": "http://2350d6c0.ngrok.io/shopify_stores/update_shop_info", 
    "format": "json" 
    } 
} 

,我使用httparty PARAMS作爲

begin 
      response = HTTParty.post("#{url}", 
      { 
      :body => [ 
       { 
        "webhook" => { 
         "topic" => "shop\/update", 
         "address" => "http:\/\/15ec3a12.ngrok.io\/shopify_stores\/update_shop_info", #place your url here 
         "format" => "json" 
        } 
       } 
         ].to_json, 
      :headers => { 'Content-Type' => 'application/json', 'Accept' => 'application/json'} 
      }) 
      byebug 
     rescue HTTParty::Error 

    end 

但repsonse是

所需參數缺失或無效

+0

好的。在「private」部分下,控制器中是否有某個部分表示「def something_params」?如果是這樣,你能把這個問題放在你的問題上嗎? –

+0

我不使用它們只是發送一個請求到服務器並保存響應 –

回答

1

最平滑的wa與HTTParty一起工作是通過創建客戶端而不是以過程方式使用它。

class MyApiClient 
    include HTTParty 
    base_uri 'example.com' 

    format :json 

    # this is just an example of how it is commonly done 
    def initalize(api_key = nil) 
    @api_key = api_key 
    end 

    def post_something(data) 
    self.class.post("/some_path", data) 
    end 
end 

這將讓你做的事:

client = MyApiClient.new() 
puts client.post_something({ foo: "bar" }) 

你不需要處理設置頁眉或編碼的身體 - HTTParty會處理,對於你。這就是圖書館的全部重點 - 如果你想用程序化的方式來哼唱,只需使用Net::HTTP這是stdlib的一部分。