簡體   English   中英

在ruby中訪問Net :: HTTP :: Post的Headers

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

我有以下一點代碼:

    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)

這通常工作正常,但另一方的服務器抱怨我的XML中的某些東西需要xml消息和正在發送的標頭的技術人員。

我有xml消息,但我無法弄清楚如何獲得上面發送的Headers。

你可以加:

https.set_debug_output $stderr

在請求之前,您將在控制台中看到發送到服務器的真實http請求。
調試這種場景非常有用。

要訪問標頭,請使用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

看一下Net :: HTTP的 post方法的文檔。 它采用uri值的path ,您要發布的數據(XML),然后是您要設置的標頭。 它將響應和主體作為雙元素數組返回。

我無法測試這個,因為你已經掩蓋了主機,並且注冊帳戶的幾率很高,但是從我記得使用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}" }

Typhoeus視為替代品,在我看來,更容易使用gem,尤其是“制作快速請求”部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM