-1

I have GET-type URLs with the parameters at the end of the URL string. I need to restructure them so that the stuff before the ? becomes the endpoint and the stuff after gets sent out as parameters in a correctly-formatted POST request payload.

For example:

http://ecample.com?test=true&message=hello

needs to be sent out as a POST request to the URL http://example.com with a request payload of:

{"test":true,"message":"hello"}

Any ideas or quick tricks to get this so I can get the POST response?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
user1051849
  • 2,307
  • 5
  • 26
  • 43
  • You can use GET style parameters as you have here, and simply change your action in the form from a GET to a POST – Khanad Aug 21 '15 at 17:34
  • "Sent out as post request" by browser or by the server? Check out [URI::Parser](http://ruby-doc.org/stdlib-2.1.0/libdoc/uri/rdoc/URI/Parser.html#method-i-parse) and [this answer](https://stackoverflow.com/questions/21990997/how-do-i-create-a-hash-from-a-querystring-in-ruby) as some places to start. – dbenton Aug 21 '15 at 17:36
  • Welcome to Stack Overflow. What have you tried? It's easier to fix your code than it is to write a tutorial or code from scratch and it lets us know you have tried and aren't just asking for us to write it for you. – the Tin Man Aug 21 '15 at 17:44

1 Answers1

1

Meditate on this:

require 'uri'

scheme, userinfo, host, port, registry, path, opaque, query, fragment = URI.split('http://example.com?test=true&message=hello')

scheme # => "http"
userinfo # => nil
host # => "example.com"
port # => nil
registry # => nil
path # => ""
opaque # => nil
query # => "test=true&message=hello"
fragment # => nil

uri = URI.parse('http://example.com?test=true&message=hello')
server = '%s://%s' % [uri.scheme, uri.host] # => "http://example.com"
parameters = Hash[URI.decode_www_form(uri.query)] # => {"test"=>"true", "message"=>"hello"}

At this point you can use whatever you want to connect to the server and send the parameters using GET, POST or any of the other request types.

URI is built into Ruby and has all the methods necessary to take apart URLs correctly and rebuild them.


When learning a computer language, it's mandatory to read through all the libraries and become familiar with their offerings. I do it many times, not to know exactly where a particular method is and its parameters, but to remember that it exists somewhere and then I can search and find it. Any modern language that can talk to web services will have such functionality available to it; It's your job to read the documentation and become familiar with it.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303