blu*_*tic 2 model-view-controller post curl ruby-on-rails request
我将如何在 Rails 设置中以以下格式发送 HTTP POST 请求:
curl https://api.venmo.com/v1/payments -d access_token=4e4sw1111111111t8an8dektggtcbb45 -d email="someemail@gmail.com" -d amount=5 -d note="Delivery."
Run Code Online (Sandbox Code Playgroud)
我想让用户将电子邮件/金额/注释参数输入到网页上的表单中,然后将该数据(当用户单击提交按钮时)传递到存储 access_token 参数的控制器中,然后触发 POST要求。
到目前为止,我已经尝试使用此方法设置控制器(并从视图 html.erb 调用它):
def make_payment
if !params[:access_token].nil?
form_data = {
"email" => @email_to,
"amount" => @amount_to,
"note" => @note_to,
"access_token" => :access_token
}
url = "https://api.venmo.com/v1/payments"
request = Net::HTTP::Post.new(url, form_data)
response = http.request(request)
end
end
Run Code Online (Sandbox Code Playgroud)
这是我当前的视图设置:
<div class="box box-warning">
<div class="box-header">
<h3 class="box-title">Pay Bill using Venmo Account</h3>
<div id="payment_note_input">
<input id="payment_note" type="text" class="form-control" required placeholder="add a note to your payment">
</div>
<div id="payment_target_input" >
<input id="payment_target" type="text" class="form-control" required placeholder="pay an email address">
</div>
<div id="payment_amount_input">
<input id="payment_amount" type="text" class="form-control" required placeholder="enter the payment amount! ">
</div>
</br>
<button class="btn btn-danger" type="button" onClick= <%=make_payment%> > Make payment</button>
</div>
Run Code Online (Sandbox Code Playgroud)
我觉得我已经接近解决方案了......
您可以使用httpparty gem来实现这一点,只需 1 行即可轻松使用:
response = HTTParty.post("https://example.com?param1=value1",
:body => {:text => data}.to_json,
:headers => {'Content-Type' => 'application/json'}
)
Run Code Online (Sandbox Code Playgroud)
如果您没有特定的正文或标题,您可以删除正文和标题,
如果你想实现 Get 请求就更简单了:
responce = HTTParty.get('http://example.com.json')
json=JSON.parse(responce.body) # in case you expect json responce
Run Code Online (Sandbox Code Playgroud)