Java Runtime.exec 转义字符串中的参数

Java Runtime.exec escaped arguments in string

由于是通过框架工作,我只能控制Runtime.getRuntime().exec(string)的命令字符串,所以没有数组。

问题是,我需要传递一些转义参数,但它似乎不起作用。

以此为例:wget -qO- --post-data "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Devices><Device><FLOWCTRL>2</FLOWCTRL></Device></Devices>" -- http://192.168.3.33/data/changes.xml。在 shell 中工作得很好,但由于我没有得到正确的响应(很可能是因为数据无效),所以有些事情搞砸了。

编辑:https://github.com/openhab/openhab-addons/blob/2.5.x/bundles/org.openhab.binding.exec/src/main/java/org/openhab/binding/exec/internal/handler/ExecHandler.java#L174Link编码

As I said, I have no control over this... I need to do it in one string :(

鉴于该约束,没有直接的解决方案。期间.

很明显,exec(String) 不理解任何形式的转义或引用。它将字符串拆分为一个命令名称和多个参数,使用空白字符作为参数分隔符。该行为是硬连线的...并记录在案。


可能的解决方案是:

  • 自己拆分,使用exec(String[])
  • 得到一个shell做拆分;例如

    String cmd = "wget -qO- --post-data \"<?xml version=\"1.0\" ...."
    Runtime.getRuntime().exec("/bin/sh", "-c", cmd);
    

    请注意,我们在这里也使用 exec(String[])

  • 即时生成并运行一个shell脚本:

    1. 将以下脚本写入临时文件(比如“/tmp/abc.sh”)

      #!/bin/sh
      wget -qO- --post-data \
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Devices><Device><FLOWCTRL>2</FLOWCTRL></Device></Devices>" \
        -- http://192.168.3.33/data/changes.xml
      
    2. 使脚本可执行

    3. 运行它:

       Runtime.getRuntime().exec("/tmp/abc.sh");