How do I make a POST request with open-uri?

旧城冷巷雨未停 提交于 2019-12-17 17:56:47

问题


Is it possible to make a POST request from Ruby with open-uri?


回答1:


Unfortunately open-uri only supports the GET verb.

You can either drop down a level and use net/http, or use rest-open-uri, which was designed to support POST and other verbs. You can do gem install rest-open-uri to install it.




回答2:


require 'open-uri'
require 'net/http'
params = {'param1' => 'value1', 'param2' => 'value2'}
url = URI.parse('http://thewebsite.com/thepath')
resp, data = Net::HTTP.post_form(url, params)
puts resp.inspect
puts data.inspect

It worked for me :)




回答3:


I'd also really recommend rest-client. It's a great base for writing an API client.




回答4:


As simple as it gets:

require 'open-uri'
require 'net/http'

response = Net::HTTP.post_form(URI.parse("https://httpbin.org/post"), { a: 1 })

puts response.code
puts response.message
puts response.body

I recommend using response.methods - Object.methods to see all the available methods, e.g. message, header,

Bonus: POST / DELETE requests:

puts Net::HTTP.new("httpbin.org").post("/post", "a=1").body
puts Net::HTTP.new("httpbin.org").delete("/delete").body


来源:https://stackoverflow.com/questions/242602/how-do-i-make-a-post-request-with-open-uri

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!