ruby - 如何在 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 # 你是说吗?字节
解决方案
如果要将文件内容用作请求体,则需要将文件内容加载到内存中,使用#read
方法:
request_body = File.open('example/file.xml').read
它会起作用的。
推荐阅读
- javascript - JQuery - 使用 !important 属性切换类
- logstash - LogStash concat Filebeat 输入
- windows - 以编程方式将打印文档存储在 Windows 中
- c# - 通过脚本在 Unity URP 光照着色器中编辑偏移值
- android - UnsupportedOperationException:Serializables 不支持默认值 - Jetpack Compose Navigation
- python - 如何使用本地模块防止 pytest
- javascript - 与 Foundation Off-canvas 的行为不一致
- react-native-android - 为什么安装反应原生导航模块后应用程序不起作用?
- git - 带有monorepos的gitflow如何命名标签
- c++ - for 循环在不满足我设置的条件的情况下完成