如何在Ruby中使用Post请求发送XML文件

如何在Ruby中使用Post请求发送XML文件,ruby,xml,ruby-on-rails-4,xmlhttprequest,net-http,Ruby,Xml,Ruby On Rails 4,Xmlhttprequest,Net Http,我正在编写一个发送http post请求的代码。现在,我在代码中编写xml主体,它可以正常工作 但如果我想使用xml文件发送请求,我会得到 #的未定义方法“bytesize” 你是说?字节 下面是我的代码 require 'net/http' request_body = <<EOF <xml_expamle> EOF uri = URI.parse('http://example') post = Net::HTTP::Post.new(uri.path, 'con

我正在编写一个发送http post请求的代码。现在,我在代码中编写xml主体,它可以正常工作

但如果我想使用xml文件发送请求,我会得到
#的未定义方法“bytesize” 你是说?字节

下面是我的代码

require 'net/http'

request_body = <<EOF
<xml_expamle>
EOF

uri = URI.parse('http://example')
post = Net::HTTP::Post.new(uri.path, 'content-type' => 'text/xml; charset=UTF-8')
post.basic_auth 'user','passcode'
Net::HTTP.new(uri.host, uri.port).start {|http|
  http.request(post, request_body) {|response|
    puts response.body
  }
}


**But if I want to make send file**

require 'net/http'

request_body = File.open('example/file.xml')


uri = URI.parse('http://example')
post = Net::HTTP::Post.new(uri.path, 'content-type' => 'application/xml; charset=UTF-8')
post.basic_auth 'user','passcode'
Net::HTTP.new(uri.host, uri.port).start {|http|
  http.request(post, request_body) {|response|
    puts response.body
  }
}
需要“net/http”
请求_body='应用程序/xml;字符集=UTF-8')
post.basic_认证“用户”,“密码”
Net::HTTP.new(uri.host,uri.port).start{HTTP|
http.request(post,request_body){response|
把反应放在身体上
}
}
我明白了 未定义的方法“bytesize”#
你是说?字节

您需要将文件内容加载到内存中如果要将其用作请求正文,请使用
#read
方法:

request_body = File.open('example/file.xml').read
它会起作用的