简体   繁体   English

在ruby中访问Net :: HTTP :: Post的Headers

[英]Accessing Headers for Net::HTTP::Post in ruby

I have the following bit of code: 我有以下一点代码:

    uri = URI.parse("https://rs.xxx-travel.com/wbsapi/RequestListenerServlet")
    https = Net::HTTP.new(uri.host,uri.port)
    https.use_ssl = true
    req = Net::HTTP::Post.new(uri.path)
    req.body = searchxml
    req["Accept-Encoding"] ='gzip'
    res = https.request(req)

This normally works fine but the server at the other side is complaining about something in my XML and the techies there need the xml message AND the headers that are being sent. 这通常工作正常,但另一方的服务器抱怨我的XML中的某些东西需要xml消息和正在发送的标头的技术人员。

I've got the xml message, but I can't work out how to get at the Headers that are being sent with the above. 我有xml消息,但我无法弄清楚如何获得上面发送的Headers。

you can add: 你可以加:

https.set_debug_output $stderr

before the request and you will see in console the real http request sent to the server. 在请求之前,您将在控制台中看到发送到服务器的真实http请求。
very useful to debug this kind of scenarios. 调试这种场景非常有用。

To access headers use the each_header method: 要访问标头,请使用each_header方法:

# Header being sent (the request object):
req.each_header do |header_name, header_value|
  puts "#{header_name} : #{header_value}"
end

# Works with the response object as well:
res.each_header do |header_name, header_value|
  puts "#{header_name} : #{header_value}"
end

Take a look at the docs for Net::HTTP's post method. 看一下Net :: HTTP的 post方法的文档。 It takes the path of the uri value, the data (XML) you want to post, then the headers you want to set. 它采用uri值的path ,您要发布的数据(XML),然后是您要设置的标头。 It returns the response and the body as a two-element array. 它将响应和主体作为双元素数组返回。

I can't test this because you've obscured the host, and odds are good it takes a registered account, but the code looks correct from what I remember when using Net::HTTP. 我无法测试这个,因为你已经掩盖了主机,并且注册帐户的几率很高,但是从我记得使用Net :: HTTP时的代码看起来是正确的。

require 'net/http'
require 'uri'

uri = URI.parse("https://rs.xxx-travel.com/wbsapi/RequestListenerServlet")
https = Net::HTTP.new(uri.host, uri.port)
https.use_ssl = true
req, body = https.post(uri.path, '<xml><blah></blah></xml>', {"Accept-Encoding" => 'gzip'})
puts "#{body.size} bytes received."
req.each{ |h,v| puts "#{h}: #{v}" }

Look at Typhoeus as an alternate, and, in my opinion, easier to use gem, especially the "Making Quick Requests" section. Typhoeus视为替代品,在我看来,更容易使用gem,尤其是“制作快速请求”部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM