Sainath Mallidi
Sainath Mallidi

Reputation: 515

Changing HTTP header in Rails

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.

Upvotes: 2

Views: 5818

Answers (2)

Sainath Mallidi
Sainath Mallidi

Reputation: 515

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" }

Upvotes: 3

Eimantas
Eimantas

Reputation: 49354

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'})

Upvotes: 0

Related Questions