首页 > 解决方案 > 如何在 Ruby 中使用 Post 请求发送 XML 文件

问题描述

我正在编写一个发送 http post 请求的代码。现在我在我的代码中编写 xml 正文,并且它工作正常。

但是,如果我想使用 xml 文件发送请求,我会得到
未定义的方法 `bytesize' for # 你的意思是?字节

我的代码如下

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
  }
}

我得到 未定义的方法 `bytesize' for # 你是说吗?字节

标签: rubyxmlruby-on-rails-4xmlhttprequestnet-http

解决方案


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

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

它会起作用的。


推荐阅读