views:

295

answers:

2

I am trying to communicate with a RESTful service in Rails. It can return data in different formats, json and xml. Is there a specific way that I can get the data type that I want.

The service mentions that ACCEPT needs to be set in HTTP header. I am not sure how to do that in Ruby.

Currently I'm doing this for get

response = Net::HTTP.get( URI.parse( <url> ) )

I have no idea on how to change the header information for this call. Any help is appreciated. Thanks.

A: 

First off you'll have to create http session object:

http_session = Net::HTTP.new( URI.parse('...').to_s, 80 )

Then you can define http headers as a hash and pass it to get method as 2nd argument:

http_session.get('/resources', {'Accept' => 'application/xml+xhtml'})
Eimantas
Say my url is`http://desktop.domain.com:28880/random/path?something=other`It throws an error when I tried the first step.. Is there something that I'm missing?
Sainath Mallidi
In first step you have to pass domain only. No path, no query. So you'll have to strip it down to the form of 'http://domain.tld'
Eimantas
+1  A: 

I have got it working this way

uri = URI( <domain>:<port>/<path> )
params = { <query_hash> }
headers = { <header_hash> }

http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.path)
request.set_form_data( params )
request = Net::HTTP::Get.new( uri.path+ '?' + request.body , headers)
response = http.request(request)

where query_hash is all the queries in hash ex: { "q" => "cats" } similarly for header_hash ex: { "ACCEPT" => "text/json" }

Sainath Mallidi