簡體   English   中英

為什么在終端和 Java 中運行 curl 命令時得到不同的結果?

[英]Why am I obtaining different results when running curl command from Terminal and in Java?

我學到了很多關於在 Java 或其衍生產品中運行curl的建議。 例如, Java 中的 curl 命令,Java使用 curl 命令等。

此外,我已經弄清楚如何使用 DOI 獲取給定資源的元數據 從這個指令中,我對使用 Java 中的一個小片段運行這個 curl 命令來處理結果非常感興趣。

讓我們舉一個例子。 URL 是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 - 你不能也不必為 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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM