通过 Net::HTTP 在 Ruby 中发送 http post 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13152264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:30:17  来源:igfitidea点击:

Sending http post request in Ruby by Net::HTTP

rubyhttphttp-headers

提问by Alan Coromano

I'm sending a request with custom headers to a web service.

我正在向 Web 服务发送带有自定义标头的请求。

require 'uri'
require 'net/http'

uri = URI("https://api.site.com/api.dll")
https = Net::HTTP.new(uri.host, uri.port)
https.use_ssl = true
headers = 
{
    'HEADER1' => "VALUE1",
    'HEADER2' => "HEADER2"
}

response = https.post(uri.path, headers) 
puts response

It's not working, I'm receiving an error of:

它不起作用,我收到以下错误:

/usr/lib/ruby/1.9.1/net/http.rb:1932:in `send_request_with_body': undefined method `bytesize' for #<Hash:0x00000001b93a10> (NoMethodError)

How do I solve this?

我该如何解决这个问题?

P.S. Ruby 1.9.3

聚苯乙烯 Ruby 1.9.3

采纳答案by qqx

The second argument of Net::HTTP#postneeds to be a Stringcontaining the data to post (often form data), the headers would be in the optional third argument.

的第二个参数Net::HTTP#post需要String包含要发布的数据(通常是表单数据),标题将在可选的第三个参数中。

回答by Arun Kumar Arjunan

Try this:

尝试这个:

For detailed documentation, take a look at: http://www.rubyinside.com/nethttp-cheat-sheet-2940.html

有关详细文档,请查看:http: //www.rubyinside.com/nethttp-cheat-sheet-2940.html

require 'uri'
require 'net/http'

uri = URI('https://api.site.com/api.dll')
https = Net::HTTP.new(uri.host, uri.port)
https.use_ssl = true

request = Net::HTTP::Post.new(uri.path)

request['HEADER1'] = 'VALUE1'
request['HEADER2'] = 'VALUE2'

response = https.request(request)
puts response

回答by davegson

As qqx mentioned, the second argument of Net::HTTP#postneeds to be a String

正如 qqx 提到的,第二个参数Net::HTTP#post需要是一个String

Luckily there's a neat function that converts a hash into the required string:

幸运的是,有一个简洁的函数可以将散列转换为所需的字符串:

response = https.post(uri.path, URI.encode_www_form(headers))