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.

1
  • Also URL is composed of path and query. <domain>/<path>?<query> Commented Jun 4, 2010 at 5:45

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

+1 Really nice, that should be more upvoted. It was hard to find a simple working example of it.
0

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

2 Comments

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?
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 'domain.tld'

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.