【问题标题】:Why am I obtaining different results when running curl command from Terminal and in Java?为什么在终端和 Java 中运行 curl 命令时会得到不同的结果?
【发布时间】:2020-10-28 17:15:45
【问题描述】:

我学到了很多在 Java 或其衍生版本中运行 curl 的建议。例如curl command in Javausing curl command in Java等。

另外,我已经知道如何fetch the metadata of a given resource using DOI。根据这条指令,我对使用 Java 中的小 sn-p 运行这个 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 格式的表单。

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

【问题讨论】:

    标签: java curl groovy metadata doi


    【解决方案1】:

    使用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]

    【讨论】:

    • 感谢您的回答。这里的重点是使用 Groovy 惯用语句来执行 Java 的样式。
    • 顺便说一句,您知道用于相同目的的等效 Java 版本吗?
    • 传递一个字符串数组而不是字符串
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-09
    • 2018-02-07
    • 2016-11-17
    • 1970-01-01
    • 2020-06-08
    • 1970-01-01
    相关资源
    最近更新 更多