如何发布包含花括号和冒号的URL
我需要对包含花括号和冒号的URL执行POST请求:
http://192.168.178.23/emoncms/input/post.json?json={power:200}&apikey=671b341330a7b1a4c20bf8ae7dd1faf1&time=12345677890
我试过这个:
uri = URI("http://192.168.178.23/emoncms/input/post.json") res = Net::HTTP.post_form(uri, "json" => "{power:200}", "apikey" => "671b341330a7b1a4c20bf8ae7dd1faf1", "time" => "1234567890")
但这会导致:
json=%7BPVCurrent%3A3.0%7D&apikey=671b341330a7b1a4c20bf8ae7dd1faf1&time=1406144643
我调用的服务无法解析此字符串。 如何强制ruby不对这些值进行编码?
必须对URL查询值进行编码,但您不会以正确的方式进行此操作。 使用设计用于操作URI的类:
require 'uri' url = URI.parse('http://192.168.178.23/emoncms/input/post.json') url.query = URI::encode_www_form( { 'json' => '{power:200}', 'apikey' => '671b341330a7b1a4c20bf8ae7dd1faf1', 'time' => 12345677890 } ) url.to_s # => "http://192.168.178.23/emoncms/input/post.json?json=%7Bpower%3A200%7D&apikey=671b341330a7b1a4c20bf8ae7dd1faf1&time=12345677890"
Ruby的内置URI和Addressable :: URI都设计用于URI。 在这两者中,Addressable :: URIfunction更齐全。
URI::encode_www_form
基本上将散列视为其内容是表单中的值,并将它们编码为URL查询。 url.query =
然后将其附加到url
。