【发布时间】:2016-10-05 11:31:16
【问题描述】:
我喜欢执行类似的 cURL 命令
curl -s -XGET 'http://localhost:xxx/h*/_count?q=*&pretty'
在我的 java 应用程序中(当然是在 linux 机器上运行)并将结果保存在字符串中。 如何正确执行此操作? This 和 this 解决方案不起作用。以下是我迄今为止的尝试和结果,基于解决方案并适应了我的情况:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
public class SyncStatus
{
public static void main(String[] args)
{
//Link 1
Process process;
try
{
process = Runtime.getRuntime().exec( "curl -s -XGET 'http://localhost:xxxx/h*/_count?q=*&pretty'");
System.out.println(process.waitFor());
System.out.println(process.getErrorStream());
System.out.println(process.getInputStream());
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
String result="";
String line=null;
while((line=input.readLine())!=null)
{
result+=line;
System.out.println("here: "+line);
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
//Results:
//1 (the Errocode)
//java.lang.UNIXProcess$ProcessPipeInputStream@2d3584f9
//java.lang.UNIXProcess$ProcessPipeInputStream@14ad0e9f
//Link 2
System.out.println("Next try:");
List list = new ArrayList();
list.add("curl");
list.add("-s");
list.add("-X");
list.add("GET");
list.add("http://localhost:9200/h*/_count?q=*&pretty");
ProcessBuilder pb = new ProcessBuilder(list);
try
{
pb.redirectErrorStream();
process = pb.start();
System.out.println(process.getErrorStream());
System.out.println(process.getInputStream());
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
//Results:
//java.lang.UNIXProcess$ProcessPipeInputStream@57dd065c
//java.lang.UNIXProcess$ProcessPipeInputStream@6fccaf14
}
}
注意:在 shell 中评估命令时,我得到了想要的结果。
【问题讨论】: