【问题标题】:curl within Ruby stripping out paramtersRuby中的curl剥离参数
【发布时间】:2016-10-03 04:27:14
【问题描述】:

出于某种原因,每当我尝试在我的 ruby​​ 控制台中调用 bash curl 命令时,它总是会删除除第一个参数之外的所有参数。谁能解释一下为什么只发送第一个参数?

例如,如果我有类似的东西

`curl -F file=@../cheddar.txt -X POST http://myapp.com/endpoint?key=cheese&action=eat&when=now&id=#{some_id}&version=#{my_version}`

后端只接受key 参数。但是,whenversion 参数都为空。在我的后端,我使用 Java google appengine,它是一个非常标准的 servlet,已经过测试并且可以与常规 curl 命令一起使用。我知道发送了第一个参数,因为如果我不发送key,那么后端会发生其他事情(同样,如果我将其他内容交换到第一个参数,则会发送)

任何想法可能会发生什么?

【问题讨论】:

标签: ruby http curl


【解决方案1】:

我认为您的 shell 正在将 & 符号作为 shell 命令读取。您需要对发送到 shell 的字符串进行转义,以便它知道这些字符是按字面意思理解的。看看这个脚本:

#!/usr/bin/env ruby

require 'shellwords'

url = 'http://myapp.com/endpoint?key=cheese&action=eat'

puts "With unescaped string:"
puts `echo #{url}`  # => "http://myapp.com/endpoint?key=cheese"
puts 'Note the absence of the last parameter action=eat'
puts "\nNow, with escaped string:"
escaped_url = Shellwords.shellescape(url)
puts `echo #{escaped_url}` # => "http://myapp.com/endpoint?key=cheese&action=eat"

Shellwords.shellescape 的作用如下:

2.3.0 :014 > Shellwords.shellescape('http://myapp.com/endpoint?key=cheese&action=eat')
 => "http://myapp.com/endpoint\\?key\\=cheese\\&action\\=eat"

另一种方法是在适当的地方插入双引号,例如:

command = %q{echo "http://myapp.com/endpoint?key=cheese&action=eat"}
puts `#{command}`

请注意,此行为与 curl 无关; curl 只是处理它从 shell 获得的任何东西。因此,您还需要使用其他 shell 命令来执行此操作。

【讨论】:

    猜你喜欢
    • 2021-12-22
    • 2014-07-12
    • 1970-01-01
    • 2012-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-20
    相关资源
    最近更新 更多