-1

I am trying to download a zip file using curl in java

public static void main(String[] args) throws Exception {

     String url = "https://abcd.com ";
     String[] command = {
              "curl", 
              " -X ", "POST ", 
              "-H ", "\"Content-Type: application/json\" ", 
              "-H ","Accept:application/json ",
              "-H ", "Accept-Encoding:gzip ", 
              "-d' ", url,
              " >> "," /Users/myUser/Documents/Test1.gzip"};

     Process p = Runtime.getRuntime().exec(command);
     p.exitValue();

}

However nothing is getting triggered . Please let me know if I have missed anything .

When I am running the same command from terminal, the zip file is getting downloaded .

azro
  • 53,056
  • 7
  • 34
  • 70
  • Try adding [Process.waitFor](https://docs.oracle.com/javase/8/docs/api/java/lang/Process.html#waitFor--) before `p.exitValue();` and check – seenukarthi Jul 24 '17 at 09:47
  • you can get the process error stream and std stream, and print them, you will know what's going on during process execution, however, why do you want to use `curl` anyway? why don't you use Java APIs to download the file? `Url` and `URLConnection`... – Yazan Jul 24 '17 at 09:48
  • Redirections don't work well with `Runtime.exec()` IIRC. I suggest using the [HttpUrlConnection](https://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html) class instead. – Aaron Jul 24 '17 at 09:48
  • @Aaron Redirection doesn't work *at all* with `Runtime.exec()`, or `ProcessBuilder.start()` either. – user207421 Jul 25 '17 at 00:46

2 Answers2

1
" >> "

Runtime.exec() does not execute a shell, and the shell is the only thing that understands >>. If you want redirection, use the redirection features of ProcessBuilder, or adjust your command to start a shell.

Notes:

  1. Difficult to understand why you're using Java at all here, rather than a shell script, or conversely if you must use Java why you're using curl. You don't need to keep a dog and bark yourself.

  2. Not much point in calling exitValue() unless you're going to do something with the result, or take some notice of the fact that the process hasn't exited yet.

user207421
  • 305,947
  • 44
  • 307
  • 483
0

This is as simple as writing a file Use apache commons-io. It has a FileUtils library that does all the work under the hood.

Essentially, after to curl the file, you need to save it to the disk (FileOutputStream) on some well defined path.

reference(also has code snippet in accepted solution): How to download and save a file from Internet using Java?