I like to execute a cURL command like
curl -s -XGET 'http://localhost:xxx/h*/_count?q=*&pretty'
in my java application (which is running of course on a linux-machine) and save the result in a String. How to do this properly? This and this solution don't work. Here are my tries and results until now, based on the solutions and adapted to my case:
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
}
}
Note: When evaluating the command in a shell, I get the desired result.