[英]Java executing curl command not working on some commands
我正在使用 Spring 和 Java 11。
我有一個測試 curl 命令,我可以通過 java 成功調用該命令。
final String cmdGetDocId = "curl -X POST https://postman-echo.com/post --data foo1=bar1&foo2=bar2";
Process process = Runtime.getRuntime().exec(cmdGetDocId);
InputStream inputStream = process.getInputStream();
JSONObject json = convertToJSON(inputStream);
返回的 JSON 符合預期。
如果我使用不同的 curl 並在命令行上執行它,它會按預期成功返回一些 JSON。
curl --location --request GET 'http://xxx.xx.xx.xx:8080/document/details/' --header 'Authorization: Basic xxxxx'
但是,如果我嘗試從我的 Java 應用程序中調用 curl,它會失敗。
String cmdGetDocId = "curl --location --request GET 'http://xxx.xx.xx.xx:8080/document/details/' --header 'Authorization: Basic xxxxx'";
Process process = Runtime.getRuntime().exec(cmdGetDocId);
InputStream inputStream = process.getInputStream();
JSONObject json = convertToJSON(inputStream);
返回的 inputStream 為空。
你知道我做錯了什么嗎? 為什么 java 方法可以調用測試 curl 而不是其他的 GET curl?
我做了一個最小的例子來解釋你一些事情:
public class Playground {
public static void main(String... args) throws IOException, InterruptedException {
String cmdGetDocId = "curl -XGET 'https://google.com'";
Process process = Runtime.getRuntime().exec(cmdGetDocId);
InputStream inputStream = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
System.out.println("output: ");
Thread.sleep(2000);
while(process.isAlive()) Thread.sleep(100);
System.out.println("return value: " + process.exitValue());
reader.lines().forEach(System.out::println);
reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
reader.lines().forEach(System.err::println);
System.out.println("---");
}
}
一方面,您必須確保,當您嘗試 output 時,該命令實際上已完成。 為了確保,我有這個骯臟的while
循環。 此外,您還想查看錯誤輸出。
此外,您實際上不想在 Java 程序中使用 cURL 。 有很多漂亮的庫,甚至是裸露的HttpURLConnection
。
嘗試這個,
String command = "curl -X POST https://postman-echo.com/post --data foo1=bar1&foo2=bar2";
ProcessBuilder builder = new ProcessBuilder(command);
builder.redirectErrorStream(true);
Process process = builder.start();
InputStream response = process.getInputStream();
這將包含錯誤(如果有),否則將包含響應。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.