Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
933 views
in Technique[技术] by (71.8m points)

ruby - How to post a URL containting curly braces and colons

I need to do a POST request for a URL containing curly braces and colons:

http://192.168.178.23/emoncms/input/post.json?json={power:200}&apikey=671b341330a7b1a4c20bf8ae7dd1faf1&time=12345677890

I tried this:

uri = URI("http://192.168.178.23/emoncms/input/post.json")

res = Net::HTTP.post_form(uri, "json" => "{power:200}", "apikey" => "671b341330a7b1a4c20bf8ae7dd1faf1", "time" => "1234567890")

But this results in:

json=%7BPVCurrent%3A3.0%7D&apikey=671b341330a7b1a4c20bf8ae7dd1faf1&time=1406144643

The service I am calling can't parse this string. How can I force ruby not to encode these values?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The URL query values have to be encoded, but you're not going about this the right way. Use a class designed to manipulate URIs:

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"

Both Ruby's built-in URI, and Addressable::URI are designed to work with URIs. Of the two, Addressable::URI is the more feature-complete.

URI::encode_www_form basically treats the hash as if its contents were the values from a form, and encodes them as a URL query. url.query = then appends that to url.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...