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?
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_jsonAny parameters passed in a GET querystring or form POST will be in the
paramshash.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.headershash: http://api.rubyonrails.org/classes/ActionDispatch/Request.html#method-i-headersHere’s how to set headers in a Net::HTTP request: