2012-07-18 87 views
4

如何在ruby中進行以下curl請求?ruby​​中的curl請求

curl -k -X GET -H "Content-Type: application/xml" -H "Accept: application/xml" -H "X-OFFERSDB-API-KEY: demo" 'http://testapi.offersdb.com/distribution/beta/offers?radius=10&postal_code=30305' 

我遇到了一些標題的困難。

require 'net/http' 

url = 'http://testapi.offersdb.com/distribution/beta/offers?radius=10&postal_code=30305' 
mykey = 'demo' 

request = Net::HTTP.new(url) 
request.request_head('/', 'X-OFFERSDB-API-KEY' => mykey) 

puts request 

回答

5

我認爲你需要創建一個請求對象,而不是一個HTTP對象。然後在其上設置標題。

require 'net/http' 

url = 'http://testapi.offersdb.com/distribution/beta/offers?radius=10&postal_code=30305' 
mykey = 'demo' 
uri = URI(url) 

request = Net::HTTP::Get.new(uri.path) 
request['Content-Type'] = 'application/xml' 
request['Accept'] = 'application/xml' 
request['X-OFFERSDB-API-KEY'] = mykey 

response = Net::HTTP.new(uri.host,uri.port) do |http| 
    http.request(request) 
end 

puts response 

來源:http://ruby-doc.org/stdlib-1.9.3/libdoc/net/http/rdoc/Net/HTTPHeader.html