运维开发网

Ruby http获取返回截断的响应

运维开发网 https://www.qedev.com 2020-07-23 22:08 出处:网络 作者:运维开发网整理
我尝试通过Postman将HTTP Get发送到设备的Restful API,它可以正常返回我期待的所有文本. Postman建议请求的 Ruby代码如下: url = URI('http://192.168.1.5/rest/op/BD1FD3D893613E79') http = Net::HTTP.new(url.host, url.port) request = Net::HTTP::Ge
我尝试通过Postman将HTTP Get发送到设备的Restful API,它可以正常返回我期待的所有文本. Postman建议请求的 Ruby代码如下:

url = URI('http://192.168.1.5/rest/op/BD1FD3D893613E79')
http = Net::HTTP.new(url.host, url.port)
request = Net::HTTP::Get.new(url)
request.basic_auth 'admin', 'admin'
request["accept"] = 'Application/json'
response = http.request(request)
puts response.read_body

但是当我在我的代码中尝试它时,它返回一个截断的响应(缺少行),我必须多次重新发送相同的Get以获得整个文本响应响应.

上面的Ruby代码中是否有任何遗漏导致此截断响应?

更新1

我试过这个

url = URI('http://192.168.1.5/rest/op/BD1FD3D893613E79')
http = Net::HTTP.new(url.host, url.port)
request = Net::HTTP::Get.new(url)
request.basic_auth 'admin', 'admin'
request["accept"] = 'Application/json'
response = http.request(request)
puts response.read_body
response.read_body do |segment|
   puts segment.to_s
end

并且生成了这个错误

IOError (Net::HTTPOK#read_body called twice):

更新2

我试过这个

1073 url = URI('http://192.168.1.5/rest/op/BD1FD3D893613E79')
1074 http = Net::HTTP.new(url.host, url.port)
1075 request = Net::HTTP::Get.new(url.to_s)
1076 request.basic_auth 'admin', 'admin'
1077 request["accept"] = 'Application/json'
1078 response = http.request(request)
1079 response.read_body do |segment|
1080   puts segment.to_s
1081 end

并得到了这个错误

IOError (Net::HTTPOK#read_body called twice):
  app/controllers/Apps_controller.rb:1079:in `block in get_config'
  app/controllers/Apps_controller.rb:1045:in `each'
  app/controllers/Apps_controller.rb:1045:in `get_config'
基于: http://ruby-doc.org/stdlib-1.9.3/libdoc/net/http/rdoc/Net/HTTPResponse.html#method-i-read_body

read_body将主体作为流返回,因此您应该迭代它,例如:

response.read_body do |segment|
  puts segment
end

如果你想获得全身,只需使用:response.body

0

精彩评论

暂无评论...
验证码 换一张
取 消