[java] How to use cURL in Java?

I am a newbie in java and wanted to use curl in java. What is my question is curl built-in in java or I have to install it from any 3rd party source to use with Java. If so, how to install curl in java. I have been googling for a long time but didnt find any help. Hope anyone can help me out there.

Thanks in advance.

This question is related to java curl

The answer is


Use Runtime to call Curl. This code works for both Ubuntu and Windows.

String[] commands = new String {"curl", "-X", "GET", "http://checkip.amazonaws.com"};
Process process = Runtime.getRuntime().exec(commands);
BufferedReader reader = new BufferedReader(new 
InputStreamReader(process.getInputStream()));
String line;
String response;
while ((line = reader.readLine()) != null) {
    response.append(line);
}

Curl is a non-java program and must be provided outside your Java program.

You can easily get much of the functionality using Jakarta Commons Net, unless there is some specific functionality like "resume transfer" you need (which is tedious to code on your own)


Using standard java libs, I suggest looking at the HttpUrlConnection class http://java.sun.com/javase/6/docs/api/java/net/HttpURLConnection.html

It can handle most of what curl can do with setting up the connection. What you do with the stream is up to you.


The Runtime object allows you to execute external command line applications from Java and would therefore allow you to use cURL however as the other answers indicate there is probably a better way to do what you are trying to do. If all you want to do is download a file the URL object will work great.


Some people have already mentioned HttpURLConnection, URL and URLConnection. If you need all the control and extra features that the curl library provides you (and more), I'd recommend Apache's httpclient.