I have some code in python that sends an http request in python, but I am trying to figure out how to do it in ruby since my server is rails.
import urllib2, sys, json
url = "http://new.openbms.org/backend/api/query"
query = "select *"
fp = urllib2.urlopen(url, data=query)
obj = json.load(fp)
json.dump(obj, sys.stdout, sort_keys=True, indent=2)
This python code actually does return what I expect, but when I try to same thing in ruby I get a bad request
require 'net/http'
query = "select *"
url = "http://new.openbms.org/backend/api/query"
uri = URI(url)
p Net::HTTP.post_form(uri, { "data" => query })
This one above print outs #<Net::HTTPBadRequest 400 Bad Request readbody=true>. Please help, thanks.
Python version 2.7.1
Ruby version 1.9.2p318
Although you’re calling the remote server as if it responds to application/x-www-form-urlencoded data, in fact it’s just responding to a command in the post body.
In Python, urllib2.urlopen’s data parameter expects a string that’s
application/x-www-form-urlencoded.select *isn’t really form encoded so to speak, but it’s working for you anyway because the server is interpreting it as a query argument namedselect *with aNonevalue, or more precisely, the server sees a post body withselect *and says “I know how to respond to that command”.So, a Ruby equivalent to what you’re doing is here.