[英]Ruby example of Net::HTTP for GET, POST, PUT, DELETE
I'm trying to learn Ruby for the first time. 我正在尝试第一次学习Ruby。 I have some experience in PHP and in PHP, I made a function like
我对PHP有一定的经验,在PHP中,我做了一个类似
function call_api(endpoint,method,arr_parameters='')
{
// do a CURL call
}
Which I would use like 我会用像
call_api('https://api.com/user','get','param=1¶m=2');
call_api('https://api.com/user/1','get');
call_api('https://api.com/user/1','post','param=1¶m=2');
call_api('https://api.com/user/1','put','param=1¶m=2');
call_api('https://api.com/user/1','delete');
So far, I've only learned how to do a GET and POST call with Ruby like so: 到目前为止,我只学习了如何使用Ruby进行GET和POST调用,如下所示:
conn = Net::HTTP.new(API_URL, API_PORT)
resppost = conn.post("/user", 'param=1', {})
respget = conn.get("/user?param=1",{})
But I don't know how to do a delete and put. 但是我不知道如何删除和放入。 Can someone show sample code for the delete and put calls with the Net::HTTP object?
有人可以显示删除的示例代码并使用Net :: HTTP对象发出呼叫吗?
I like the Faraday gem. 我喜欢法拉第宝石。 I find its design the simplest.
我发现它的设计最简单。
Once you gem install faraday
you can require 'faraday'
and do: 一旦你
gem install faraday
你可以require 'faraday'
并做:
result = Faraday.get('http://google.es')
You can also POST, PUT, DELETE, etc. 您也可以POST,PUT,DELETE等。
Faraday.delete('http://google.es')
Faraday.post('http://google.es', {some_parameter: 'hello'})
Project: https://github.com/lostisland/faraday 项目: https : //github.com/lostisland/faraday
You would just namespace it: 您只需为其命名空间:
Net::HTTP::Put.new(uri)
Same with delete: 与删除相同:
Net::HTTP::Delete.new(uri)
You can even do that with your existing calls: 您甚至可以使用现有的电话进行操作:
conn = Net::HTTP.new(uri)
con.get(path)
that is equivalent to: 这相当于:
Net::HTTP::Get.new(uri)
For DELETE you can use conn.delete("/user/1", {})
or 对于DELETE,可以使用
conn.delete("/user/1", {})
或
request = Net::HTTP::Delete.new("/user/1")
response = conn.request(request)
For PUT, 对于PUT,
response = http.set_request('PUT', "/user/1", "param=1")
or Net::HTTP::Put.new(path)
或
Net::HTTP::Put.new(path)
Can I suggest a look at httparty ? 我可以建议看看httparty吗? They offer some really awesome examples right on their page to do exactly what you want to do.
他们在页面上提供了一些非常出色的示例,可以准确地完成您想做的事情。
response = HTTParty.get('https://api.stackexchange.com/2.2/questions?site=stackoverflow')
puts response.body, response.code, response.message, response.headers.inspect
And many more examples of calling different endpoints. 还有更多调用不同端点的例子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.