Ruby未定义的方法`bytesize'用于#<Hash:0x2954fe8>

Cru*_*633 15 ruby net-http

我有以下Ruby代码,用于沙盒模式的跟踪网站:

require "net/http"
require "net/https"
require "uri"

xml = <<XML
<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?><data appname="dhl_entwicklerportal" language-code="de" password="Dhl_123!" request="get-status-for-public-user"><data piece-code="00340433836536550280"></data></data>
XML

uri = URI('https://cig.dhl.de/services/sandbox/rest/sendungsverfolgung')

nhttp = Net::HTTP.new(uri.host, uri.port)
nhttp.use_ssl=true
nhttp.verify_mode=OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Get.new(uri)
request.basic_auth 'xpackageWP', 'hidden'
response = nhttp.start {|http|
http.request(request, xml:xml)
}

puts response.body
Run Code Online (Sandbox Code Playgroud)

我总是得到错误:

d:/Ruby200/lib/ruby/2.0.0/net/http/generic_request.rb:179:in `send_request_with_body' undefined method `bytesize' for #<Hash:0x2954fe8> (NoMethodError)
from d:/Ruby200/lib/ruby/2.0.0/net/http/generic_request.rb:130:in `exec'
from d:/Ruby200/lib/ruby/2.0.0/net/http.rb:1404:in `block in transport_request'
from d:/Ruby200/lib/ruby/2.0.0/net/http.rb:1403:in `catch'
from d:/Ruby200/lib/ruby/2.0.0/net/http.rb:1403:in `transport_request'
from d:/Ruby200/lib/ruby/2.0.0/net/http.rb:1376:in `request'
from D:/Dropbox_5BHIF/Dropbox/TempDHL/Main.rb:17:in `block in <main>'
from d:/Ruby200/lib/ruby/2.0.0/net/http.rb:852:in `start'
from D:/Dropbox_5BHIF/Dropbox/TempDHL/Main.rb:16:in `<main>'
Run Code Online (Sandbox Code Playgroud)

我努力解决这个问题,但我想不出任何问题.当我在浏览器中用链接测试它然后一个?xml =它完美地工作,所以它似乎是我的Ruby代码的问题.

fal*_*tru 33

您将发布数据作为哈希发送.你应该把它编码为字符串.

例如使用URI::encode_www_form:

request = Net::HTTP::Post.new(uri)
...
response = nhttp.start do |http|
  post_data = URI.encode_www_form({xml: xml})
  http.request(request, post_data)
end
Run Code Online (Sandbox Code Playgroud)

更新如果您需要GET请求,请将查询字符串附加到网址.

post_data = URI.encode_www_form({xml: xml})
uri = URI('https://cig.dhl.de/services/sandbox/rest/sendungsverfolgung?' +
          post_data)

...

response = nhttp.start do |http|
  http.request(request)
end
Run Code Online (Sandbox Code Playgroud)