1

我学到了很多curl在 Java 或其衍生产品中运行的建议。例如,Java 中的 curl 命令,Java使用 curl 命令等。

此外,我已经弄清楚如何使用 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 格式的表单。

问题是:我在这里做错了什么?你们有没有遇到过这个问题?

4

1 回答 1

2

Usingexec不是一个 shell - 你不能也不必为 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]改用。

于 2020-10-28T17:54:49.293 回答