在Terminal和Java中运行curl命令时,为什么会得到不同的结果?

问题描述

我已经学到了很多建议,可以在Java或其派生版本中运行curl。例如curl command in Javausing curl command in Java

我还想出了如何fetch the metadata of a given resource using DOI。通过此指令,我对使用Java中的一小段代码来运行该curl命令以处理结果非常感兴趣。

举个例子。网址为http://dx.doi.org/10.1016/j.immuni.2015.09.001

从终端运行curl命令

curl -LH "Accept: application/x-bibtex" http://dx.doi.org/10.1016/j.immuni.2015.09.001

输出看起来像

@article{Biswas_2015,doi = {10.1016/j.immuni.2015.09.001},url = {https://doi.org/10.1016%2Fj.immuni.2015.09.001},year = 2015,month = {sep},publisher = {Elsevier {BV}},volume = {43},number = {3},pages = {435--449},author = {Subhra~K. Biswas},title = {Metabolic Reprogramming of Immune Cells in Cancer Progression},journal = {Immunity}

在Groovy中运行此curl命令

回收此站点上共享的一些代码,我编写了以下过程。

Map result = [:]
String command = "curl -LH 'Accept: application/x-bibtex' http://dx.doi.org/10.1016/j.immuni.2015.09.001"
Process process = Runtime.getRuntime().exec(command)
InputStream stream = process.getInputStream()
result.put("data",stream.text)
process.destroy()

我得到的是整个HTML页面,而不是我的期望的BibTeX格式。

问题是:我在这里做错了什么?你们中有人遇到过该问题吗?

解决方法

使用exec不是shell,您可以也不必引用 一个外壳,那是不存在的。默认情况下,另外exec(String)个使用 一个字符串标记器(基本上在空格处分割)使其 对于任何稍微高级的用例,尤其没有用。

您很可能总是会更好地使用接受的版本 该命令的字符串数组(+ args)。

您有效呼叫的位置看起来像这样(请注意, 命令在空格处被分割了-所以我用\'来制作我的shell 忽略它):

# curl -LH \'Accept: application/x-bibtex\' http://dx.doi.org/10.1016/j.immuni.2015.09.001
curl: (6) Could not resolve host: application
... HTML ...

使用groovy的最短路径如下所示(请注意,exec 具有用于传递字符串数组的版本):

groovy:000> ["curl","-LH","Accept: application/x-bibtex","http://dx.doi.org/10.1016/j.immuni.2015.09.001"].execute().text
===> @article{Biswas_2015,9doi = {10.1016/j.immuni.2015.09.001},9url = {https://doi.org/10.1016%2Fj.immuni.2015.09.001},9year = 2015,9month = {sep},9publisher = {Elsevier {BV}},9volume = {43},9number = {3},9pages = {435--449},9author = {Subhra~K. Biswas},9title = {Metabolic Reprogramming of Immune Cells in Cancer Progression},9journal = {Immunity}
}

如果您需要“ shell-isms”,请改用["sh","-c",command]

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...