Search code examples
ruby-on-railsrubyhttpruby-on-rails-3httpwebrequest

How to set client 'header' and 'params' values for a HTTP GET request and read those in the service server?


I am using Ruby on Rails 3 and I would like to set header and params values for a HTTP GET request of a client server. Then, on the other side, I would like to read those on the service server.

What I do in the client is:

host = "http://<site_name>.com"
path = "/users/1.json"
query_params = ["username=test_username", "password=test_psw"].join("&")

uri = URI.parse("#{host}#{path}?#{query_params}")

http = Net::HTTP.new(uri.host, uri.port)

http.start do
  @response_test = JSON(http.get("#{host}#{path}").body)["user"]
end

What I do in the service is:

...
respond_to do |format|
  format.json {
    render :json => @user.to_json
    if ( params["username"] == "test_username" && password == test_psw )
      render :json => @user.to_json
    else
      render :text => "Bad request"
    end
  }
end

All above code doesn't work correctly: making the HTTP GET request I get always a 706: unexpected token at 'Bad request'.

(1) How set correctly the header in the client? In the example above, are params correctly set?

(2) How to read properly header and params values in the server?


Solution

  • Are you getting the "706: unexpected token at 'Bad request'" error on the client side after attempting to parse the response? If so I would guess this is because your client appears to be expecting a JSON response, and you're sending the unquoted raw text "Bad request", which does not parse as valid JSON. Try render :json => "Bad request".to_json

    Any parameters passed in a GET querystring or form POST will be in the params hash.

    In answer to your questions:

    1) You can see your params by putting puts "params: #{params.inspect}" inside your controller action.

    2) Headers are available in the request.headers hash: http://api.rubyonrails.org/classes/ActionDispatch/Request.html#method-i-headers

    Here's how to set headers in a Net::HTTP request:

    url = URI.parse("http://www.whatismyip.com/automation/n09230945.asp")
    
    req = Net::HTTP::Get.new(url.path)
    req.add_field("X-Forwarded-For", "0.0.0.0")
    
    res = Net::HTTP.new(url.host, url.port).start do |http|
      http.request(req)
    end