【问题标题】:How to send XML file using Post request in Ruby如何在 Ruby 中使用 Post 请求发送 XML 文件
【发布时间】:2019-11-25 04:19:57
【问题描述】:

我正在编写一个发送 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
  }
}

我明白了 未定义的方法 `bytesize' 用于# 你的意思是?字节

【问题讨论】:

    标签: ruby xml ruby-on-rails-4 xmlhttprequest net-http


    【解决方案1】:

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

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

    它会起作用的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-29
      • 1970-01-01
      • 2019-01-13
      • 1970-01-01
      • 2016-03-31
      相关资源
      最近更新 更多