maksim korshikov
maksim korshikov

Reputation: 73

How to send XML file using Post request in Ruby

I am writing a code that send http post request. Now I write xml body in my code, and its working correctly.

But if I want to send request using xml file I get
undefined method `bytesize' for # Did you mean? bytes

My code below

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

I get undefined method `bytesize' for # Did you mean? bytes

Upvotes: 1

Views: 2012

Answers (1)

mrzasa
mrzasa

Reputation: 23307

You need to load the file content to memory if you want to use it as a request body, use #read method:

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

and it'll work.

Upvotes: 1

Related Questions