从GET结构化URL发送POST请求

时间:2015-08-21 17:28:00

标签: ruby ruby-on-rails-4 post

我有GET类型的URL,其中的参数位于URL字符串的末尾。我需要对它们进行重组,以便?之前的内容成为端点,之后的内容将作为参数发送到正确格式化的POST请求有效负载中。

例如:

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

需要作为POST请求发送到URL http://example.com,请求有效负载为:

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

任何想法或快速技巧,以便我可以获得POST响应?

1 个答案:

答案 0 :(得分:1)

默想:

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

此时,您可以使用任何想要连接到server的内容,并使用GET,POST或任何其他请求类型发送parameters

URI内置于Ruby中,具有正确拆分URL并重建它们所需的所有方法。

学习计算机语言时,必须阅读所有图书馆并熟悉其产品。我做了很多次,不知道具体方法的确切位置及其参数,但要记住它存在于某处,然后我可以搜索并找到它。任何可以与Web服务通信的现代语言都可以使用这些功能;阅读文档并熟悉它是你的工作。

相关问题