2

I want to execute a Linux command (curl) using java code

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class ExecuteShellCommand {

    public String executeCommand(String command) {
        StringBuffer output = new StringBuffer();

        Process p;
        try {
            p = Runtime.getRuntime().exec(command);
            p.waitFor();
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

            String line = "";
            while ((line = reader.readLine()) != null) {
                output.append(line + "\n");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return output.toString();

    }

    public static void main(String args[]) {

        ExecuteShellCommand com = new ExecuteShellCommand();


            System.out.println(com.executeCommand(
                    "curl -u '<username><pw>' -k <host>/services/search/jobs -d search=\"abc""));

        System.out.println("hello"); 

The console output is printing hello only with no errors though when i tried the command in git bash it will give a xml response.

joshua
  • 177
  • 1
  • 12
  • could you please change command to something simpler like: "curl google.com" – Tashkhisi Jun 13 '20 at 08:16
  • Does this answer your question? [Java Runtime.getRuntime(): getting output from executing a command line program](https://stackoverflow.com/questions/5711084/java-runtime-getruntime-getting-output-from-executing-a-command-line-program) – Joe Jun 13 '20 at 08:23
  • Actually the curl command I need to execute takes input as username and password and is searching some table from where we will get some specific id as a response (XML) and with that id as a parameter I have to execute another curl command to get the response. – joshua Jun 13 '20 at 08:33
  • 1
    Why not just use any of the available HTTP clients ([HttpURLConnection](https://docs.oracle.com/javase/8/docs/api/java/net/HttpURLConnection.html), [HttpClient](https://docs.oracle.com/javase/9/docs/api/jdk/incubator/http/HttpClient.html), [Apache HTTP client](https://hc.apache.org/httpcomponents-client-ga/), [OkHttp](https://square.github.io/okhttp), …) and make a call without spawning a child process? It will be faster, cleaner and more portable. – madhead Jun 13 '20 at 12:02
  • Do you have any sample code or something related to that. Actually I have no idea about this ,working on something like this for the first time. – joshua Jun 13 '20 at 14:18

0 Answers0